babylon.max.js 4.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597
  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. if (this._getFromCache(baseName)) {
  221. this._prepareEffect();
  222. return;
  223. }
  224. var vertexSource;
  225. var fragmentSource;
  226. if (baseName.vertexElement) {
  227. vertexSource = document.getElementById(baseName.vertexElement);
  228. if (!vertexSource) {
  229. vertexSource = baseName.vertexElement;
  230. }
  231. }
  232. else {
  233. vertexSource = baseName.vertex || baseName;
  234. }
  235. if (baseName.fragmentElement) {
  236. fragmentSource = document.getElementById(baseName.fragmentElement);
  237. if (!fragmentSource) {
  238. fragmentSource = baseName.fragmentElement;
  239. }
  240. }
  241. else {
  242. fragmentSource = baseName.fragment || baseName;
  243. }
  244. var finalVertexCode;
  245. this._loadVertexShaderAsync(vertexSource)
  246. .then(function (vertexCode) {
  247. return _this._processIncludesAsync(vertexCode);
  248. })
  249. .then(function (vertexCodeWithIncludes) {
  250. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  251. return _this._loadFragmentShaderAsync(fragmentSource);
  252. })
  253. .then(function (fragmentCode) {
  254. return _this._processIncludesAsync(fragmentCode);
  255. })
  256. .then(function (fragmentCodeWithIncludes) {
  257. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  258. if (baseName) {
  259. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  260. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  261. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  262. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  263. }
  264. else {
  265. _this._vertexSourceCode = finalVertexCode;
  266. _this._fragmentSourceCode = migratedFragmentCode;
  267. }
  268. _this._setInCache(baseName);
  269. _this._prepareEffect();
  270. });
  271. }
  272. Effect.prototype._getSourceCacheKey = function (baseName) {
  273. var cacheKey = baseName;
  274. if (this._indexParameters) {
  275. for (var key in this._indexParameters) {
  276. if (this._indexParameters.hasOwnProperty(key)) {
  277. cacheKey += "|";
  278. cacheKey += key;
  279. cacheKey += "_";
  280. cacheKey += this._indexParameters[key];
  281. }
  282. }
  283. }
  284. return cacheKey;
  285. };
  286. Effect.prototype._getFromCache = function (baseName) {
  287. if (typeof baseName !== "string") {
  288. return false;
  289. }
  290. var cacheKey = this._getSourceCacheKey(baseName);
  291. var sources = Effect._sourceCache[cacheKey];
  292. if (!sources) {
  293. return false;
  294. }
  295. this._vertexSourceCode = sources.vertex;
  296. this._fragmentSourceCode = sources.fragment;
  297. return true;
  298. };
  299. Effect.prototype._setInCache = function (baseName) {
  300. if (typeof baseName !== "string") {
  301. return;
  302. }
  303. var cacheKey = this._getSourceCacheKey(baseName);
  304. Effect._sourceCache[cacheKey] = {
  305. vertex: this._vertexSourceCode,
  306. fragment: this._fragmentSourceCode
  307. };
  308. };
  309. Object.defineProperty(Effect.prototype, "key", {
  310. /**
  311. * Unique key for this effect
  312. */
  313. get: function () {
  314. return this._key;
  315. },
  316. enumerable: true,
  317. configurable: true
  318. });
  319. /**
  320. * If the effect has been compiled and prepared.
  321. * @returns if the effect is compiled and prepared.
  322. */
  323. Effect.prototype.isReady = function () {
  324. return this._isReady;
  325. };
  326. /**
  327. * The engine the effect was initialized with.
  328. * @returns the engine.
  329. */
  330. Effect.prototype.getEngine = function () {
  331. return this._engine;
  332. };
  333. /**
  334. * The compiled webGL program for the effect
  335. * @returns the webGL program.
  336. */
  337. Effect.prototype.getProgram = function () {
  338. return this._program;
  339. };
  340. /**
  341. * The set of names of attribute variables for the shader.
  342. * @returns An array of attribute names.
  343. */
  344. Effect.prototype.getAttributesNames = function () {
  345. return this._attributesNames;
  346. };
  347. /**
  348. * Returns the attribute at the given index.
  349. * @param index The index of the attribute.
  350. * @returns The location of the attribute.
  351. */
  352. Effect.prototype.getAttributeLocation = function (index) {
  353. return this._attributes[index];
  354. };
  355. /**
  356. * Returns the attribute based on the name of the variable.
  357. * @param name of the attribute to look up.
  358. * @returns the attribute location.
  359. */
  360. Effect.prototype.getAttributeLocationByName = function (name) {
  361. var index = this._attributesNames.indexOf(name);
  362. return this._attributes[index];
  363. };
  364. /**
  365. * The number of attributes.
  366. * @returns the numnber of attributes.
  367. */
  368. Effect.prototype.getAttributesCount = function () {
  369. return this._attributes.length;
  370. };
  371. /**
  372. * Gets the index of a uniform variable.
  373. * @param uniformName of the uniform to look up.
  374. * @returns the index.
  375. */
  376. Effect.prototype.getUniformIndex = function (uniformName) {
  377. return this._uniformsNames.indexOf(uniformName);
  378. };
  379. /**
  380. * Returns the attribute based on the name of the variable.
  381. * @param uniformName of the uniform to look up.
  382. * @returns the location of the uniform.
  383. */
  384. Effect.prototype.getUniform = function (uniformName) {
  385. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  386. };
  387. /**
  388. * Returns an array of sampler variable names
  389. * @returns The array of sampler variable neames.
  390. */
  391. Effect.prototype.getSamplers = function () {
  392. return this._samplers;
  393. };
  394. /**
  395. * The error from the last compilation.
  396. * @returns the error string.
  397. */
  398. Effect.prototype.getCompilationError = function () {
  399. return this._compilationError;
  400. };
  401. /**
  402. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  403. * @param func The callback to be used.
  404. */
  405. Effect.prototype.executeWhenCompiled = function (func) {
  406. if (this.isReady()) {
  407. func(this);
  408. return;
  409. }
  410. this.onCompileObservable.add(function (effect) {
  411. func(effect);
  412. });
  413. };
  414. /** @ignore */
  415. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (vertex instanceof HTMLElement) {
  419. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  420. return Promise.resolve(vertexCode);
  421. }
  422. }
  423. // Base64 encoded ?
  424. if (vertex.substr(0, 7) === "base64:") {
  425. var vertexBinary = window.atob(vertex.substr(7));
  426. return Promise.resolve(vertexBinary);
  427. }
  428. // Is in local store ?
  429. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  430. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  431. }
  432. var vertexShaderUrl;
  433. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  434. vertexShaderUrl = vertex;
  435. }
  436. else {
  437. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  438. }
  439. // Vertex shader
  440. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  441. };
  442. /** @ignore */
  443. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  444. if (BABYLON.Tools.IsWindowObjectExist()) {
  445. // DOM element ?
  446. if (fragment instanceof HTMLElement) {
  447. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  448. return Promise.resolve(fragmentCode);
  449. }
  450. }
  451. // Base64 encoded ?
  452. if (fragment.substr(0, 7) === "base64:") {
  453. var fragmentBinary = window.atob(fragment.substr(7));
  454. return Promise.resolve(fragmentBinary);
  455. }
  456. // Is in local store ?
  457. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  458. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  459. }
  460. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  461. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  462. }
  463. var fragmentShaderUrl;
  464. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  465. fragmentShaderUrl = fragment;
  466. }
  467. else {
  468. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  469. }
  470. // Fragment shader
  471. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  472. };
  473. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  474. // Rebuild shaders source code
  475. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  476. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  477. vertexCode = prefix + vertexCode;
  478. fragmentCode = prefix + fragmentCode;
  479. // Number lines of shaders source code
  480. var i = 2;
  481. var regex = /\n/gm;
  482. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  483. i = 2;
  484. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  485. // Dump shaders name and formatted source code
  486. if (this.name.vertexElement) {
  487. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  488. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  489. }
  490. else if (this.name.vertex) {
  491. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  492. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  493. }
  494. else {
  495. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  496. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  497. }
  498. };
  499. ;
  500. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  501. var preparedSourceCode = this._processPrecision(sourceCode);
  502. if (this._engine.webGLVersion == 1) {
  503. return preparedSourceCode;
  504. }
  505. // Already converted
  506. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  507. return preparedSourceCode.replace("#version 300 es", "");
  508. }
  509. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  510. // Remove extensions
  511. // #extension GL_OES_standard_derivatives : enable
  512. // #extension GL_EXT_shader_texture_lod : enable
  513. // #extension GL_EXT_frag_depth : enable
  514. // #extension GL_EXT_draw_buffers : require
  515. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  516. var result = preparedSourceCode.replace(regex, "");
  517. // Migrate to GLSL v300
  518. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  519. result = result.replace(/attribute[ \t]/g, "in ");
  520. result = result.replace(/[ \t]attribute/g, " in");
  521. if (isFragment) {
  522. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  523. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  524. result = result.replace(/texture2D\s*\(/g, "texture(");
  525. result = result.replace(/textureCube\s*\(/g, "texture(");
  526. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  527. result = result.replace(/gl_FragColor/g, "glFragColor");
  528. result = result.replace(/gl_FragData/g, "glFragData");
  529. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  530. }
  531. return result;
  532. };
  533. Effect.prototype._processIncludesAsync = function (sourceCode) {
  534. var _this = this;
  535. return new Promise(function (resolve, reject) {
  536. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  537. var match = regex.exec(sourceCode);
  538. var returnValue = sourceCode;
  539. while (match != null) {
  540. var includeFile = match[1];
  541. // Uniform declaration
  542. if (includeFile.indexOf("__decl__") !== -1) {
  543. includeFile = includeFile.replace(/__decl__/, "");
  544. if (_this._engine.supportsUniformBuffers) {
  545. includeFile = includeFile.replace(/Vertex/, "Ubo");
  546. includeFile = includeFile.replace(/Fragment/, "Ubo");
  547. }
  548. includeFile = includeFile + "Declaration";
  549. }
  550. if (Effect.IncludesShadersStore[includeFile]) {
  551. // Substitution
  552. var includeContent = Effect.IncludesShadersStore[includeFile];
  553. if (match[2]) {
  554. var splits = match[3].split(",");
  555. for (var index = 0; index < splits.length; index += 2) {
  556. var source = new RegExp(splits[index], "g");
  557. var dest = splits[index + 1];
  558. includeContent = includeContent.replace(source, dest);
  559. }
  560. }
  561. if (match[4]) {
  562. var indexString = match[5];
  563. if (indexString.indexOf("..") !== -1) {
  564. var indexSplits = indexString.split("..");
  565. var minIndex = parseInt(indexSplits[0]);
  566. var maxIndex = parseInt(indexSplits[1]);
  567. var sourceIncludeContent = includeContent.slice(0);
  568. includeContent = "";
  569. if (isNaN(maxIndex)) {
  570. maxIndex = _this._indexParameters[indexSplits[1]];
  571. }
  572. for (var i = minIndex; i < maxIndex; i++) {
  573. if (!_this._engine.supportsUniformBuffers) {
  574. // Ubo replacement
  575. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  576. return p1 + "{X}";
  577. });
  578. }
  579. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  580. }
  581. }
  582. else {
  583. if (!_this._engine.supportsUniformBuffers) {
  584. // Ubo replacement
  585. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  586. return p1 + "{X}";
  587. });
  588. }
  589. includeContent = includeContent.replace(/\{X\}/g, indexString);
  590. }
  591. }
  592. // Replace
  593. returnValue = returnValue.replace(match[0], includeContent);
  594. }
  595. else {
  596. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  597. _this._engine._loadFileAsync(includeShaderUrl)
  598. .then(function (fileContent) {
  599. Effect.IncludesShadersStore[includeFile] = fileContent;
  600. return _this._processIncludesAsync(returnValue);
  601. })
  602. .then(function (returnValue) {
  603. resolve(returnValue);
  604. });
  605. return;
  606. }
  607. match = regex.exec(sourceCode);
  608. }
  609. resolve(returnValue);
  610. });
  611. };
  612. Effect.prototype._processPrecision = function (source) {
  613. if (source.indexOf("precision highp float") === -1) {
  614. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  615. source = "precision mediump float;\n" + source;
  616. }
  617. else {
  618. source = "precision highp float;\n" + source;
  619. }
  620. }
  621. else {
  622. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  623. source = source.replace("precision highp float", "precision mediump float");
  624. }
  625. }
  626. return source;
  627. };
  628. /**
  629. * Recompiles the webGL program
  630. * @param vertexSourceCode The source code for the vertex shader.
  631. * @param fragmentSourceCode The source code for the fragment shader.
  632. * @param onCompiled Callback called when completed.
  633. * @param onError Callback called on error.
  634. */
  635. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  636. var _this = this;
  637. this._isReady = false;
  638. this._vertexSourceCodeOverride = vertexSourceCode;
  639. this._fragmentSourceCodeOverride = fragmentSourceCode;
  640. this.onError = function (effect, error) {
  641. if (onError) {
  642. onError(error);
  643. }
  644. };
  645. this.onCompiled = function () {
  646. var scenes = _this.getEngine().scenes;
  647. for (var i = 0; i < scenes.length; i++) {
  648. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  649. }
  650. if (onCompiled) {
  651. onCompiled(_this._program);
  652. }
  653. };
  654. this._fallbacks = null;
  655. this._prepareEffect();
  656. };
  657. /**
  658. * Gets the uniform locations of the the specified variable names
  659. * @param names THe names of the variables to lookup.
  660. * @returns Array of locations in the same order as variable names.
  661. */
  662. Effect.prototype.getSpecificUniformLocations = function (names) {
  663. var engine = this._engine;
  664. return engine.getUniforms(this._program, names);
  665. };
  666. /**
  667. * Prepares the effect
  668. */
  669. Effect.prototype._prepareEffect = function () {
  670. var attributesNames = this._attributesNames;
  671. var defines = this.defines;
  672. var fallbacks = this._fallbacks;
  673. this._valueCache = {};
  674. var previousProgram = this._program;
  675. try {
  676. var engine = this._engine;
  677. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  678. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  679. }
  680. else {
  681. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  682. }
  683. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  684. if (engine.supportsUniformBuffers) {
  685. for (var name in this._uniformBuffersNames) {
  686. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  687. }
  688. }
  689. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  690. this._attributes = engine.getAttributes(this._program, attributesNames);
  691. var index;
  692. for (index = 0; index < this._samplers.length; index++) {
  693. var sampler = this.getUniform(this._samplers[index]);
  694. if (sampler == null) {
  695. this._samplers.splice(index, 1);
  696. index--;
  697. }
  698. }
  699. engine.bindSamplers(this);
  700. this._compilationError = "";
  701. this._isReady = true;
  702. if (this.onCompiled) {
  703. this.onCompiled(this);
  704. }
  705. this.onCompileObservable.notifyObservers(this);
  706. this.onCompileObservable.clear();
  707. // Unbind mesh reference in fallbacks
  708. if (this._fallbacks) {
  709. this._fallbacks.unBindMesh();
  710. }
  711. if (previousProgram) {
  712. this.getEngine()._deleteProgram(previousProgram);
  713. }
  714. }
  715. catch (e) {
  716. this._compilationError = e.message;
  717. // Let's go through fallbacks then
  718. BABYLON.Tools.Error("Unable to compile effect:");
  719. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  720. return " " + uniform;
  721. }));
  722. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  723. return " " + attribute;
  724. }));
  725. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  726. BABYLON.Tools.Error("Error: " + this._compilationError);
  727. if (previousProgram) {
  728. this._program = previousProgram;
  729. this._isReady = true;
  730. if (this.onError) {
  731. this.onError(this, this._compilationError);
  732. }
  733. this.onErrorObservable.notifyObservers(this);
  734. }
  735. if (fallbacks && fallbacks.isMoreFallbacks) {
  736. BABYLON.Tools.Error("Trying next fallback.");
  737. this.defines = fallbacks.reduce(this.defines, this);
  738. this._prepareEffect();
  739. }
  740. else {
  741. if (this.onError) {
  742. this.onError(this, this._compilationError);
  743. }
  744. this.onErrorObservable.notifyObservers(this);
  745. this.onErrorObservable.clear();
  746. // Unbind mesh reference in fallbacks
  747. if (this._fallbacks) {
  748. this._fallbacks.unBindMesh();
  749. }
  750. }
  751. }
  752. };
  753. Object.defineProperty(Effect.prototype, "isSupported", {
  754. /**
  755. * Checks if the effect is supported. (Must be called after compilation)
  756. */
  757. get: function () {
  758. return this._compilationError === "";
  759. },
  760. enumerable: true,
  761. configurable: true
  762. });
  763. /**
  764. * Binds a texture to the engine to be used as output of the shader.
  765. * @param channel Name of the output variable.
  766. * @param texture Texture to bind.
  767. */
  768. Effect.prototype._bindTexture = function (channel, texture) {
  769. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  770. };
  771. /**
  772. * Sets a texture on the engine to be used in the shader.
  773. * @param channel Name of the sampler variable.
  774. * @param texture Texture to set.
  775. */
  776. Effect.prototype.setTexture = function (channel, texture) {
  777. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  778. };
  779. /**
  780. * Sets an array of textures on the engine to be used in the shader.
  781. * @param channel Name of the variable.
  782. * @param textures Textures to set.
  783. */
  784. Effect.prototype.setTextureArray = function (channel, textures) {
  785. if (this._samplers.indexOf(channel + "Ex") === -1) {
  786. var initialPos = this._samplers.indexOf(channel);
  787. for (var index = 1; index < textures.length; index++) {
  788. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  789. }
  790. }
  791. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  792. };
  793. /**
  794. * 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)
  795. * @param channel Name of the sampler variable.
  796. * @param postProcess Post process to get the input texture from.
  797. */
  798. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  799. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  800. };
  801. /** @ignore */
  802. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  803. var cache = this._valueCache[uniformName];
  804. var flag = matrix.updateFlag;
  805. if (cache !== undefined && cache === flag) {
  806. return false;
  807. }
  808. this._valueCache[uniformName] = flag;
  809. return true;
  810. };
  811. /** @ignore */
  812. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  813. var cache = this._valueCache[uniformName];
  814. if (!cache) {
  815. cache = [x, y];
  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. return changed;
  829. };
  830. /** @ignore */
  831. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y, z];
  835. this._valueCache[uniformName] = cache;
  836. return true;
  837. }
  838. var changed = false;
  839. if (cache[0] !== x) {
  840. cache[0] = x;
  841. changed = true;
  842. }
  843. if (cache[1] !== y) {
  844. cache[1] = y;
  845. changed = true;
  846. }
  847. if (cache[2] !== z) {
  848. cache[2] = z;
  849. changed = true;
  850. }
  851. return changed;
  852. };
  853. /** @ignore */
  854. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  855. var cache = this._valueCache[uniformName];
  856. if (!cache) {
  857. cache = [x, y, z, w];
  858. this._valueCache[uniformName] = cache;
  859. return true;
  860. }
  861. var changed = false;
  862. if (cache[0] !== x) {
  863. cache[0] = x;
  864. changed = true;
  865. }
  866. if (cache[1] !== y) {
  867. cache[1] = y;
  868. changed = true;
  869. }
  870. if (cache[2] !== z) {
  871. cache[2] = z;
  872. changed = true;
  873. }
  874. if (cache[3] !== w) {
  875. cache[3] = w;
  876. changed = true;
  877. }
  878. return changed;
  879. };
  880. /**
  881. * Binds a buffer to a uniform.
  882. * @param buffer Buffer to bind.
  883. * @param name Name of the uniform variable to bind to.
  884. */
  885. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  886. var bufferName = this._uniformBuffersNames[name];
  887. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  888. return;
  889. }
  890. Effect._baseCache[bufferName] = buffer;
  891. this._engine.bindUniformBufferBase(buffer, bufferName);
  892. };
  893. /**
  894. * Binds block to a uniform.
  895. * @param blockName Name of the block to bind.
  896. * @param index Index to bind.
  897. */
  898. Effect.prototype.bindUniformBlock = function (blockName, index) {
  899. this._engine.bindUniformBlock(this._program, blockName, index);
  900. };
  901. /**
  902. * Sets an interger value on a uniform variable.
  903. * @param uniformName Name of the variable.
  904. * @param value Value to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setInt = function (uniformName, value) {
  908. var cache = this._valueCache[uniformName];
  909. if (cache !== undefined && cache === value)
  910. return this;
  911. this._valueCache[uniformName] = value;
  912. this._engine.setInt(this.getUniform(uniformName), value);
  913. return this;
  914. };
  915. /**
  916. * Sets an int array on a uniform variable.
  917. * @param uniformName Name of the variable.
  918. * @param array array to be set.
  919. * @returns this effect.
  920. */
  921. Effect.prototype.setIntArray = function (uniformName, array) {
  922. this._valueCache[uniformName] = null;
  923. this._engine.setIntArray(this.getUniform(uniformName), array);
  924. return this;
  925. };
  926. /**
  927. * 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)
  928. * @param uniformName Name of the variable.
  929. * @param array array to be set.
  930. * @returns this effect.
  931. */
  932. Effect.prototype.setIntArray2 = function (uniformName, array) {
  933. this._valueCache[uniformName] = null;
  934. this._engine.setIntArray2(this.getUniform(uniformName), array);
  935. return this;
  936. };
  937. /**
  938. * 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)
  939. * @param uniformName Name of the variable.
  940. * @param array array to be set.
  941. * @returns this effect.
  942. */
  943. Effect.prototype.setIntArray3 = function (uniformName, array) {
  944. this._valueCache[uniformName] = null;
  945. this._engine.setIntArray3(this.getUniform(uniformName), array);
  946. return this;
  947. };
  948. /**
  949. * 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)
  950. * @param uniformName Name of the variable.
  951. * @param array array to be set.
  952. * @returns this effect.
  953. */
  954. Effect.prototype.setIntArray4 = function (uniformName, array) {
  955. this._valueCache[uniformName] = null;
  956. this._engine.setIntArray4(this.getUniform(uniformName), array);
  957. return this;
  958. };
  959. /**
  960. * Sets an float array on a uniform variable.
  961. * @param uniformName Name of the variable.
  962. * @param array array to be set.
  963. * @returns this effect.
  964. */
  965. Effect.prototype.setFloatArray = function (uniformName, array) {
  966. this._valueCache[uniformName] = null;
  967. this._engine.setFloatArray(this.getUniform(uniformName), array);
  968. return this;
  969. };
  970. /**
  971. * 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)
  972. * @param uniformName Name of the variable.
  973. * @param array array to be set.
  974. * @returns this effect.
  975. */
  976. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  977. this._valueCache[uniformName] = null;
  978. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  979. return this;
  980. };
  981. /**
  982. * 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)
  983. * @param uniformName Name of the variable.
  984. * @param array array to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  988. this._valueCache[uniformName] = null;
  989. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  990. return this;
  991. };
  992. /**
  993. * 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)
  994. * @param uniformName Name of the variable.
  995. * @param array array to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  999. this._valueCache[uniformName] = null;
  1000. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1001. return this;
  1002. };
  1003. /**
  1004. * Sets an array on a uniform variable.
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setArray = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setArray(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * 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)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setArray2 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setArray2(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * 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)
  1027. * @param uniformName Name of the variable.
  1028. * @param array array to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setArray3 = function (uniformName, array) {
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setArray3(this.getUniform(uniformName), array);
  1034. return this;
  1035. };
  1036. /**
  1037. * 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)
  1038. * @param uniformName Name of the variable.
  1039. * @param array array to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setArray4 = function (uniformName, array) {
  1043. this._valueCache[uniformName] = null;
  1044. this._engine.setArray4(this.getUniform(uniformName), array);
  1045. return this;
  1046. };
  1047. /**
  1048. * Sets matrices on a uniform variable.
  1049. * @param uniformName Name of the variable.
  1050. * @param matrices matrices to be set.
  1051. * @returns this effect.
  1052. */
  1053. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1054. if (!matrices) {
  1055. return this;
  1056. }
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets matrix on a uniform variable.
  1063. * @param uniformName Name of the variable.
  1064. * @param matrix matrix to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1068. if (this._cacheMatrix(uniformName, matrix)) {
  1069. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1070. }
  1071. return this;
  1072. };
  1073. /**
  1074. * 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)
  1075. * @param uniformName Name of the variable.
  1076. * @param matrix matrix to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1086. * @param uniformName Name of the variable.
  1087. * @param matrix matrix to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets a float on a uniform variable.
  1097. * @param uniformName Name of the variable.
  1098. * @param value value to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat = function (uniformName, value) {
  1102. var cache = this._valueCache[uniformName];
  1103. if (cache !== undefined && cache === value)
  1104. return this;
  1105. this._valueCache[uniformName] = value;
  1106. this._engine.setFloat(this.getUniform(uniformName), value);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets a boolean on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param bool value to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setBool = function (uniformName, bool) {
  1116. var cache = this._valueCache[uniformName];
  1117. if (cache !== undefined && cache === bool)
  1118. return this;
  1119. this._valueCache[uniformName] = bool;
  1120. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets a Vector2 on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param vector2 vector2 to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1130. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1131. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a float2 on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param x First float in float2.
  1139. * @param y Second float in float2.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1143. if (this._cacheFloat2(uniformName, x, y)) {
  1144. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a Vector3 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param vector3 Value to be set.
  1152. * @returns this effect.
  1153. */
  1154. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1155. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1156. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Sets a float3 on a uniform variable.
  1162. * @param uniformName Name of the variable.
  1163. * @param x First float in float3.
  1164. * @param y Second float in float3.
  1165. * @param z Third float in float3.
  1166. * @returns this effect.
  1167. */
  1168. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1169. if (this._cacheFloat3(uniformName, x, y, z)) {
  1170. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1171. }
  1172. return this;
  1173. };
  1174. /**
  1175. * Sets a Vector4 on a uniform variable.
  1176. * @param uniformName Name of the variable.
  1177. * @param vector4 Value to be set.
  1178. * @returns this effect.
  1179. */
  1180. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1181. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1182. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1183. }
  1184. return this;
  1185. };
  1186. /**
  1187. * Sets a float4 on a uniform variable.
  1188. * @param uniformName Name of the variable.
  1189. * @param x First float in float4.
  1190. * @param y Second float in float4.
  1191. * @param z Third float in float4.
  1192. * @param w Fourth float in float4.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1196. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1197. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1198. }
  1199. return this;
  1200. };
  1201. /**
  1202. * Sets a Color3 on a uniform variable.
  1203. * @param uniformName Name of the variable.
  1204. * @param color3 Value to be set.
  1205. * @returns this effect.
  1206. */
  1207. Effect.prototype.setColor3 = function (uniformName, color3) {
  1208. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1209. this._engine.setColor3(this.getUniform(uniformName), color3);
  1210. }
  1211. return this;
  1212. };
  1213. /**
  1214. * Sets a Color4 on a uniform variable.
  1215. * @param uniformName Name of the variable.
  1216. * @param color3 Value to be set.
  1217. * @param alpha Alpha value to be set.
  1218. * @returns this effect.
  1219. */
  1220. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1221. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1222. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1223. }
  1224. return this;
  1225. };
  1226. /**
  1227. * Sets a Color4 on a uniform variable
  1228. * @param uniformName defines the name of the variable
  1229. * @param color4 defines the value to be set
  1230. * @returns this effect.
  1231. */
  1232. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1233. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1234. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1235. }
  1236. return this;
  1237. };
  1238. /**
  1239. * Resets the cache of effects.
  1240. */
  1241. Effect.ResetCache = function () {
  1242. Effect._baseCache = {};
  1243. };
  1244. Effect._uniqueIdSeed = 0;
  1245. Effect._baseCache = {};
  1246. Effect._sourceCache = {};
  1247. // Statics
  1248. /**
  1249. * Store of each shader (The can be looked up using effect.key)
  1250. */
  1251. Effect.ShadersStore = {};
  1252. /**
  1253. * Store of each included file for a shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.IncludesShadersStore = {};
  1256. return Effect;
  1257. }());
  1258. BABYLON.Effect = Effect;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.effect.js.map
  1261. //# sourceMappingURL=babylon.types.js.map
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var KeyboardEventTypes = /** @class */ (function () {
  1265. function KeyboardEventTypes() {
  1266. }
  1267. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1268. get: function () {
  1269. return KeyboardEventTypes._KEYDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1275. get: function () {
  1276. return KeyboardEventTypes._KEYUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. KeyboardEventTypes._KEYDOWN = 0x01;
  1282. KeyboardEventTypes._KEYUP = 0x02;
  1283. return KeyboardEventTypes;
  1284. }());
  1285. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1286. var KeyboardInfo = /** @class */ (function () {
  1287. function KeyboardInfo(type, event) {
  1288. this.type = type;
  1289. this.event = event;
  1290. }
  1291. return KeyboardInfo;
  1292. }());
  1293. BABYLON.KeyboardInfo = KeyboardInfo;
  1294. /**
  1295. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1296. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1297. */
  1298. var KeyboardInfoPre = /** @class */ (function (_super) {
  1299. __extends(KeyboardInfoPre, _super);
  1300. function KeyboardInfoPre(type, event) {
  1301. var _this = _super.call(this, type, event) || this;
  1302. _this.skipOnPointerObservable = false;
  1303. return _this;
  1304. }
  1305. return KeyboardInfoPre;
  1306. }(KeyboardInfo));
  1307. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1308. })(BABYLON || (BABYLON = {}));
  1309. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1310. var BABYLON;
  1311. (function (BABYLON) {
  1312. var PointerEventTypes = /** @class */ (function () {
  1313. function PointerEventTypes() {
  1314. }
  1315. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1316. get: function () {
  1317. return PointerEventTypes._POINTERDOWN;
  1318. },
  1319. enumerable: true,
  1320. configurable: true
  1321. });
  1322. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1323. get: function () {
  1324. return PointerEventTypes._POINTERUP;
  1325. },
  1326. enumerable: true,
  1327. configurable: true
  1328. });
  1329. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1330. get: function () {
  1331. return PointerEventTypes._POINTERMOVE;
  1332. },
  1333. enumerable: true,
  1334. configurable: true
  1335. });
  1336. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1337. get: function () {
  1338. return PointerEventTypes._POINTERWHEEL;
  1339. },
  1340. enumerable: true,
  1341. configurable: true
  1342. });
  1343. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1344. get: function () {
  1345. return PointerEventTypes._POINTERPICK;
  1346. },
  1347. enumerable: true,
  1348. configurable: true
  1349. });
  1350. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1351. get: function () {
  1352. return PointerEventTypes._POINTERTAP;
  1353. },
  1354. enumerable: true,
  1355. configurable: true
  1356. });
  1357. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1358. get: function () {
  1359. return PointerEventTypes._POINTERDOUBLETAP;
  1360. },
  1361. enumerable: true,
  1362. configurable: true
  1363. });
  1364. PointerEventTypes._POINTERDOWN = 0x01;
  1365. PointerEventTypes._POINTERUP = 0x02;
  1366. PointerEventTypes._POINTERMOVE = 0x04;
  1367. PointerEventTypes._POINTERWHEEL = 0x08;
  1368. PointerEventTypes._POINTERPICK = 0x10;
  1369. PointerEventTypes._POINTERTAP = 0x20;
  1370. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1371. return PointerEventTypes;
  1372. }());
  1373. BABYLON.PointerEventTypes = PointerEventTypes;
  1374. var PointerInfoBase = /** @class */ (function () {
  1375. function PointerInfoBase(type, event) {
  1376. this.type = type;
  1377. this.event = event;
  1378. }
  1379. return PointerInfoBase;
  1380. }());
  1381. BABYLON.PointerInfoBase = PointerInfoBase;
  1382. /**
  1383. * This class is used to store pointer related info for the onPrePointerObservable event.
  1384. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1385. */
  1386. var PointerInfoPre = /** @class */ (function (_super) {
  1387. __extends(PointerInfoPre, _super);
  1388. function PointerInfoPre(type, event, localX, localY) {
  1389. var _this = _super.call(this, type, event) || this;
  1390. _this.skipOnPointerObservable = false;
  1391. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1392. return _this;
  1393. }
  1394. return PointerInfoPre;
  1395. }(PointerInfoBase));
  1396. BABYLON.PointerInfoPre = PointerInfoPre;
  1397. /**
  1398. * This type contains all the data related to a pointer event in Babylon.js.
  1399. * 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.
  1400. */
  1401. var PointerInfo = /** @class */ (function (_super) {
  1402. __extends(PointerInfo, _super);
  1403. function PointerInfo(type, event, pickInfo) {
  1404. var _this = _super.call(this, type, event) || this;
  1405. _this.pickInfo = pickInfo;
  1406. return _this;
  1407. }
  1408. return PointerInfo;
  1409. }(PointerInfoBase));
  1410. BABYLON.PointerInfo = PointerInfo;
  1411. })(BABYLON || (BABYLON = {}));
  1412. //# sourceMappingURL=babylon.pointerEvents.js.map
  1413. var BABYLON;
  1414. (function (BABYLON) {
  1415. BABYLON.ToGammaSpace = 1 / 2.2;
  1416. BABYLON.ToLinearSpace = 2.2;
  1417. BABYLON.Epsilon = 0.001;
  1418. /**
  1419. * Class used to hold a RBG color
  1420. */
  1421. var Color3 = /** @class */ (function () {
  1422. /**
  1423. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1424. * @param r defines the red component (between 0 and 1, default is 0)
  1425. * @param g defines the green component (between 0 and 1, default is 0)
  1426. * @param b defines the blue component (between 0 and 1, default is 0)
  1427. */
  1428. function Color3(
  1429. /**
  1430. * Defines the red component (between 0 and 1, default is 0)
  1431. */
  1432. r,
  1433. /**
  1434. * Defines the green component (between 0 and 1, default is 0)
  1435. */
  1436. g,
  1437. /**
  1438. * Defines the blue component (between 0 and 1, default is 0)
  1439. */
  1440. b) {
  1441. if (r === void 0) { r = 0; }
  1442. if (g === void 0) { g = 0; }
  1443. if (b === void 0) { b = 0; }
  1444. this.r = r;
  1445. this.g = g;
  1446. this.b = b;
  1447. }
  1448. /**
  1449. * Creates a string with the Color3 current values
  1450. * @returns the string representation of the Color3 object
  1451. */
  1452. Color3.prototype.toString = function () {
  1453. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1454. };
  1455. /**
  1456. * Returns the string "Color3"
  1457. * @returns "Color3"
  1458. */
  1459. Color3.prototype.getClassName = function () {
  1460. return "Color3";
  1461. };
  1462. /**
  1463. * Compute the Color3 hash code
  1464. * @returns an unique number that can be used to hash Color3 objects
  1465. */
  1466. Color3.prototype.getHashCode = function () {
  1467. var hash = this.r || 0;
  1468. hash = (hash * 397) ^ (this.g || 0);
  1469. hash = (hash * 397) ^ (this.b || 0);
  1470. return hash;
  1471. };
  1472. // Operators
  1473. /**
  1474. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1475. * @param array defines the array where to store the r,g,b components
  1476. * @param index defines an optional index in the target array to define where to start storing values
  1477. * @returns the current Color3 object
  1478. */
  1479. Color3.prototype.toArray = function (array, index) {
  1480. if (index === undefined) {
  1481. index = 0;
  1482. }
  1483. array[index] = this.r;
  1484. array[index + 1] = this.g;
  1485. array[index + 2] = this.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1490. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1491. * @returns a new {BABYLON.Color4} object
  1492. */
  1493. Color3.prototype.toColor4 = function (alpha) {
  1494. if (alpha === void 0) { alpha = 1; }
  1495. return new Color4(this.r, this.g, this.b, alpha);
  1496. };
  1497. /**
  1498. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1499. * @returns the new array
  1500. */
  1501. Color3.prototype.asArray = function () {
  1502. var result = new Array();
  1503. this.toArray(result, 0);
  1504. return result;
  1505. };
  1506. /**
  1507. * Returns the luminance value
  1508. * @returns a float value
  1509. */
  1510. Color3.prototype.toLuminance = function () {
  1511. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1512. };
  1513. /**
  1514. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1515. * @param otherColor defines the second operand
  1516. * @returns the new Color3 object
  1517. */
  1518. Color3.prototype.multiply = function (otherColor) {
  1519. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1520. };
  1521. /**
  1522. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1523. * @param otherColor defines the second operand
  1524. * @param result defines the Color3 object where to store the result
  1525. * @returns the current Color3
  1526. */
  1527. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1528. result.r = this.r * otherColor.r;
  1529. result.g = this.g * otherColor.g;
  1530. result.b = this.b * otherColor.b;
  1531. return this;
  1532. };
  1533. /**
  1534. * Determines equality between Color3 objects
  1535. * @param otherColor defines the second operand
  1536. * @returns true if the rgb values are equal to the passed ones
  1537. */
  1538. Color3.prototype.equals = function (otherColor) {
  1539. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1540. };
  1541. /**
  1542. * Determines equality between the current Color3 object and a set of r,b,g values
  1543. * @param r defines the red component to check
  1544. * @param g defines the green component to check
  1545. * @param b defines the blue component to check
  1546. * @returns true if the rgb values are equal to the passed ones
  1547. */
  1548. Color3.prototype.equalsFloats = function (r, g, b) {
  1549. return this.r === r && this.g === g && this.b === b;
  1550. };
  1551. /**
  1552. * Multiplies in place each rgb value by scale
  1553. * @param scale defines the scaling factor
  1554. * @returns the updated Color3.
  1555. */
  1556. Color3.prototype.scale = function (scale) {
  1557. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1558. };
  1559. /**
  1560. * Multiplies the rgb values by scale and stores the result into "result"
  1561. * @param scale defines the scaling factor
  1562. * @param result defines the Color3 object where to store the result
  1563. * @returns the unmodified current Color3.
  1564. */
  1565. Color3.prototype.scaleToRef = function (scale, result) {
  1566. result.r = this.r * scale;
  1567. result.g = this.g * scale;
  1568. result.b = this.b * scale;
  1569. return this;
  1570. };
  1571. /**
  1572. * Clamps the rgb values by the min and max values and stores the result into "result"
  1573. * @param min defines minimum clamping value (default is 0)
  1574. * @param max defines maximum clamping value (default is 1)
  1575. * @param result defines color to store the result into
  1576. * @returns the original Color3
  1577. */
  1578. Color3.prototype.clampToRef = function (min, max, result) {
  1579. if (min === void 0) { min = 0; }
  1580. if (max === void 0) { max = 1; }
  1581. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1582. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1583. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1584. return this;
  1585. };
  1586. /**
  1587. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1588. * @param otherColor defines the second operand
  1589. * @returns the new Color3
  1590. */
  1591. Color3.prototype.add = function (otherColor) {
  1592. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1593. };
  1594. /**
  1595. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1596. * @param otherColor defines the second operand
  1597. * @param result defines Color3 object to store the result into
  1598. * @returns the unmodified current Color3
  1599. */
  1600. Color3.prototype.addToRef = function (otherColor, result) {
  1601. result.r = this.r + otherColor.r;
  1602. result.g = this.g + otherColor.g;
  1603. result.b = this.b + otherColor.b;
  1604. return this;
  1605. };
  1606. /**
  1607. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.subtract = function (otherColor) {
  1612. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.subtractToRef = function (otherColor, result) {
  1621. result.r = this.r - otherColor.r;
  1622. result.g = this.g - otherColor.g;
  1623. result.b = this.b - otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Copy the current object
  1628. * @returns a new Color3 copied the current one
  1629. */
  1630. Color3.prototype.clone = function () {
  1631. return new Color3(this.r, this.g, this.b);
  1632. };
  1633. /**
  1634. * Copies the rgb values from the source in the current Color3
  1635. * @param source defines the source Color3 object
  1636. * @returns the updated Color3 object
  1637. */
  1638. Color3.prototype.copyFrom = function (source) {
  1639. this.r = source.r;
  1640. this.g = source.g;
  1641. this.b = source.b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the passed floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.copyFromFloats = function (r, g, b) {
  1652. this.r = r;
  1653. this.g = g;
  1654. this.b = b;
  1655. return this;
  1656. };
  1657. /**
  1658. * Updates the Color3 rgb values from the passed floats
  1659. * @param r defines the red component to read from
  1660. * @param g defines the green component to read from
  1661. * @param b defines the blue component to read from
  1662. * @returns the current Color3 object
  1663. */
  1664. Color3.prototype.set = function (r, g, b) {
  1665. return this.copyFromFloats(r, g, b);
  1666. };
  1667. /**
  1668. * Compute the Color3 hexadecimal code as a string
  1669. * @returns a string containing the hexadecimal representation of the Color3 object
  1670. */
  1671. Color3.prototype.toHexString = function () {
  1672. var intR = (this.r * 255) | 0;
  1673. var intG = (this.g * 255) | 0;
  1674. var intB = (this.b * 255) | 0;
  1675. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1676. };
  1677. /**
  1678. * Computes a new Color3 converted from the current one to linear space
  1679. * @returns a new Color3 object
  1680. */
  1681. Color3.prototype.toLinearSpace = function () {
  1682. var convertedColor = new Color3();
  1683. this.toLinearSpaceToRef(convertedColor);
  1684. return convertedColor;
  1685. };
  1686. /**
  1687. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1688. * @param convertedColor defines the Color3 object where to store the linear space version
  1689. * @returns the unmodified Color3
  1690. */
  1691. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1692. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1693. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1694. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1695. return this;
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to gamma space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toGammaSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toGammaSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the gamma space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1715. return this;
  1716. };
  1717. // Statics
  1718. /**
  1719. * Creates a new Color3 from the string containing valid hexadecimal values
  1720. * @param hex defines a string containing valid hexadecimal values
  1721. * @returns a new Color3 object
  1722. */
  1723. Color3.FromHexString = function (hex) {
  1724. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1725. return new Color3(0, 0, 0);
  1726. }
  1727. var r = parseInt(hex.substring(1, 3), 16);
  1728. var g = parseInt(hex.substring(3, 5), 16);
  1729. var b = parseInt(hex.substring(5, 7), 16);
  1730. return Color3.FromInts(r, g, b);
  1731. };
  1732. /**
  1733. * Creates a new Vector3 from the starting index of the passed array
  1734. * @param array defines the source array
  1735. * @param offset defines an offset in the source array
  1736. * @returns a new Color3 object
  1737. */
  1738. Color3.FromArray = function (array, offset) {
  1739. if (offset === void 0) { offset = 0; }
  1740. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1741. };
  1742. /**
  1743. * Creates a new Color3 from integer values (< 256)
  1744. * @param r defines the red component to read from (value between 0 and 255)
  1745. * @param g defines the green component to read from (value between 0 and 255)
  1746. * @param b defines the blue component to read from (value between 0 and 255)
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.FromInts = function (r, g, b) {
  1750. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1751. };
  1752. /**
  1753. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1754. * @param start defines the start Color3 value
  1755. * @param end defines the end Color3 value
  1756. * @param amount defines the gradient value between start and end
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Lerp = function (start, end, amount) {
  1760. var r = start.r + ((end.r - start.r) * amount);
  1761. var g = start.g + ((end.g - start.g) * amount);
  1762. var b = start.b + ((end.b - start.b) * amount);
  1763. return new Color3(r, g, b);
  1764. };
  1765. /**
  1766. * Returns a Color3 value containing a red color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Red = function () { return new Color3(1, 0, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a green color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Green = function () { return new Color3(0, 1, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a blue color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a black color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Black = function () { return new Color3(0, 0, 0); };
  1785. /**
  1786. * Returns a Color3 value containing a white color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.White = function () { return new Color3(1, 1, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a purple color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1795. /**
  1796. * Returns a Color3 value containing a magenta color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a yellow color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a gray color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1810. /**
  1811. * Returns a Color3 value containing a teal color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1815. /**
  1816. * Returns a Color3 value containing a random color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1820. return Color3;
  1821. }());
  1822. BABYLON.Color3 = Color3;
  1823. /**
  1824. * Class used to hold a RBGA color
  1825. */
  1826. var Color4 = /** @class */ (function () {
  1827. /**
  1828. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1829. * @param r defines the red component (between 0 and 1, default is 0)
  1830. * @param g defines the green component (between 0 and 1, default is 0)
  1831. * @param b defines the blue component (between 0 and 1, default is 0)
  1832. * @param a defines the alpha component (between 0 and 1, default is 1)
  1833. */
  1834. function Color4(
  1835. /**
  1836. * Defines the red component (between 0 and 1, default is 0)
  1837. */
  1838. r,
  1839. /**
  1840. * Defines the green component (between 0 and 1, default is 0)
  1841. */
  1842. g,
  1843. /**
  1844. * Defines the blue component (between 0 and 1, default is 0)
  1845. */
  1846. b,
  1847. /**
  1848. * Defines the alpha component (between 0 and 1, default is 1)
  1849. */
  1850. a) {
  1851. if (r === void 0) { r = 0; }
  1852. if (g === void 0) { g = 0; }
  1853. if (b === void 0) { b = 0; }
  1854. if (a === void 0) { a = 1; }
  1855. this.r = r;
  1856. this.g = g;
  1857. this.b = b;
  1858. this.a = a;
  1859. }
  1860. // Operators
  1861. /**
  1862. * Adds in place the passed Color4 values to the current Color4 object
  1863. * @param right defines the second operand
  1864. * @returns the current updated Color4 object
  1865. */
  1866. Color4.prototype.addInPlace = function (right) {
  1867. this.r += right.r;
  1868. this.g += right.g;
  1869. this.b += right.b;
  1870. this.a += right.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1875. * @returns the new array
  1876. */
  1877. Color4.prototype.asArray = function () {
  1878. var result = new Array();
  1879. this.toArray(result, 0);
  1880. return result;
  1881. };
  1882. /**
  1883. * Stores from the starting index in the passed array the Color4 successive values
  1884. * @param array defines the array where to store the r,g,b components
  1885. * @param index defines an optional index in the target array to define where to start storing values
  1886. * @returns the current Color4 object
  1887. */
  1888. Color4.prototype.toArray = function (array, index) {
  1889. if (index === undefined) {
  1890. index = 0;
  1891. }
  1892. array[index] = this.r;
  1893. array[index + 1] = this.g;
  1894. array[index + 2] = this.b;
  1895. array[index + 3] = this.a;
  1896. return this;
  1897. };
  1898. /**
  1899. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1900. * @param right defines the second operand
  1901. * @returns a new Color4 object
  1902. */
  1903. Color4.prototype.add = function (right) {
  1904. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1905. };
  1906. /**
  1907. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1908. * @param right defines the second operand
  1909. * @returns a new Color4 object
  1910. */
  1911. Color4.prototype.subtract = function (right) {
  1912. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1913. };
  1914. /**
  1915. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1916. * @param right defines the second operand
  1917. * @param result defines the Color4 object where to store the result
  1918. * @returns the current Color4 object
  1919. */
  1920. Color4.prototype.subtractToRef = function (right, result) {
  1921. result.r = this.r - right.r;
  1922. result.g = this.g - right.g;
  1923. result.b = this.b - right.b;
  1924. result.a = this.a - right.a;
  1925. return this;
  1926. };
  1927. /**
  1928. * Creates a new Color4 with the current Color4 values multiplied by scale
  1929. * @param scale defines the scaling factor to apply
  1930. * @returns a new Color4 object
  1931. */
  1932. Color4.prototype.scale = function (scale) {
  1933. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1934. };
  1935. /**
  1936. * Multiplies the current Color4 values by scale and stores the result in "result"
  1937. * @param scale defines the scaling factor to apply
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the current Color4.
  1940. */
  1941. Color4.prototype.scaleToRef = function (scale, result) {
  1942. result.r = this.r * scale;
  1943. result.g = this.g * scale;
  1944. result.b = this.b * scale;
  1945. result.a = this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the passed Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the passed float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the passed float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the passed array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. var Vector2 = /** @class */ (function () {
  2196. /**
  2197. * Creates a new Vector2 from the passed x and y coordinates.
  2198. */
  2199. function Vector2(x, y) {
  2200. this.x = x;
  2201. this.y = y;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector2 coordinates.
  2205. */
  2206. Vector2.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector2"
  2211. */
  2212. Vector2.prototype.getClassName = function () {
  2213. return "Vector2";
  2214. };
  2215. /**
  2216. * Returns the Vector2 hash code as a number.
  2217. */
  2218. Vector2.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. return hash;
  2222. };
  2223. // Operators
  2224. /**
  2225. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2226. * Returns the Vector2.
  2227. */
  2228. Vector2.prototype.toArray = function (array, index) {
  2229. if (index === void 0) { index = 0; }
  2230. array[index] = this.x;
  2231. array[index + 1] = this.y;
  2232. return this;
  2233. };
  2234. /**
  2235. * Returns a new array with 2 elements : the Vector2 coordinates.
  2236. */
  2237. Vector2.prototype.asArray = function () {
  2238. var result = new Array();
  2239. this.toArray(result, 0);
  2240. return result;
  2241. };
  2242. /**
  2243. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2244. * Returns the updated Vector2.
  2245. */
  2246. Vector2.prototype.copyFrom = function (source) {
  2247. this.x = source.x;
  2248. this.y = source.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the passed floats.
  2253. * Returns the updated Vector2.
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the passed floats.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2269. */
  2270. Vector2.prototype.add = function (otherVector) {
  2271. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2272. };
  2273. /**
  2274. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2275. * Returns the Vector2.
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2284. * Returns the updated Vector2.
  2285. */
  2286. Vector2.prototype.addInPlace = function (otherVector) {
  2287. this.x += otherVector.x;
  2288. this.y += otherVector.y;
  2289. return this;
  2290. };
  2291. /**
  2292. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2299. */
  2300. Vector2.prototype.subtract = function (otherVector) {
  2301. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2305. * Returns the Vector2.
  2306. */
  2307. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2314. * Returns the updated Vector2.
  2315. */
  2316. Vector2.prototype.subtractInPlace = function (otherVector) {
  2317. this.x -= otherVector.x;
  2318. this.y -= otherVector.y;
  2319. return this;
  2320. };
  2321. /**
  2322. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2323. * Returns the updated Vector2.
  2324. */
  2325. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2326. this.x *= otherVector.x;
  2327. this.y *= otherVector.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2332. */
  2333. Vector2.prototype.multiply = function (otherVector) {
  2334. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2335. };
  2336. /**
  2337. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2338. * Returns the Vector2.
  2339. */
  2340. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2341. result.x = this.x * otherVector.x;
  2342. result.y = this.y * otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2347. */
  2348. Vector2.prototype.multiplyByFloats = function (x, y) {
  2349. return new Vector2(this.x * x, this.y * y);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2353. */
  2354. Vector2.prototype.divide = function (otherVector) {
  2355. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2356. };
  2357. /**
  2358. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2359. * Returns the Vector2.
  2360. */
  2361. Vector2.prototype.divideToRef = function (otherVector, result) {
  2362. result.x = this.x / otherVector.x;
  2363. result.y = this.y / otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Divides the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector2.prototype.divideInPlace = function (otherVector) {
  2371. return this.divideToRef(otherVector, this);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 with current Vector2 negated coordinates.
  2375. */
  2376. Vector2.prototype.negate = function () {
  2377. return new Vector2(-this.x, -this.y);
  2378. };
  2379. /**
  2380. * Multiply the Vector2 coordinates by scale.
  2381. * Returns the updated Vector2.
  2382. */
  2383. Vector2.prototype.scaleInPlace = function (scale) {
  2384. this.x *= scale;
  2385. this.y *= scale;
  2386. return this;
  2387. };
  2388. /**
  2389. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2390. */
  2391. Vector2.prototype.scale = function (scale) {
  2392. return new Vector2(this.x * scale, this.y * scale);
  2393. };
  2394. /**
  2395. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2396. */
  2397. Vector2.prototype.equals = function (otherVector) {
  2398. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2399. };
  2400. /**
  2401. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2402. */
  2403. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2404. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2405. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2406. };
  2407. // Properties
  2408. /**
  2409. * Returns the vector length (float).
  2410. */
  2411. Vector2.prototype.length = function () {
  2412. return Math.sqrt(this.x * this.x + this.y * this.y);
  2413. };
  2414. /**
  2415. * Returns the vector squared length (float);
  2416. */
  2417. Vector2.prototype.lengthSquared = function () {
  2418. return (this.x * this.x + this.y * this.y);
  2419. };
  2420. // Methods
  2421. /**
  2422. * Normalize the vector.
  2423. * Returns the updated Vector2.
  2424. */
  2425. Vector2.prototype.normalize = function () {
  2426. var len = this.length();
  2427. if (len === 0)
  2428. return this;
  2429. var num = 1.0 / len;
  2430. this.x *= num;
  2431. this.y *= num;
  2432. return this;
  2433. };
  2434. /**
  2435. * Returns a new Vector2 copied from the Vector2.
  2436. */
  2437. Vector2.prototype.clone = function () {
  2438. return new Vector2(this.x, this.y);
  2439. };
  2440. // Statics
  2441. /**
  2442. * Returns a new Vector2(0, 0)
  2443. */
  2444. Vector2.Zero = function () {
  2445. return new Vector2(0, 0);
  2446. };
  2447. /**
  2448. * Returns a new Vector2(1, 1)
  2449. */
  2450. Vector2.One = function () {
  2451. return new Vector2(1, 1);
  2452. };
  2453. /**
  2454. * Returns a new Vector2 set from the passed index element of the passed array.
  2455. */
  2456. Vector2.FromArray = function (array, offset) {
  2457. if (offset === void 0) { offset = 0; }
  2458. return new Vector2(array[offset], array[offset + 1]);
  2459. };
  2460. /**
  2461. * Sets "result" from the passed index element of the passed array.
  2462. */
  2463. Vector2.FromArrayToRef = function (array, offset, result) {
  2464. result.x = array[offset];
  2465. result.y = array[offset + 1];
  2466. };
  2467. /**
  2468. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2469. */
  2470. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2471. var squared = amount * amount;
  2472. var cubed = amount * squared;
  2473. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2474. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2475. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2476. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2477. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2478. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2479. return new Vector2(x, y);
  2480. };
  2481. /**
  2482. * 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".
  2483. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2484. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2485. */
  2486. Vector2.Clamp = function (value, min, max) {
  2487. var x = value.x;
  2488. x = (x > max.x) ? max.x : x;
  2489. x = (x < min.x) ? min.x : x;
  2490. var y = value.y;
  2491. y = (y > max.y) ? max.y : y;
  2492. y = (y < min.y) ? min.y : y;
  2493. return new Vector2(x, y);
  2494. };
  2495. /**
  2496. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2497. */
  2498. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2499. var squared = amount * amount;
  2500. var cubed = amount * squared;
  2501. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2502. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2503. var part3 = (cubed - (2.0 * squared)) + amount;
  2504. var part4 = cubed - squared;
  2505. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2506. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2507. return new Vector2(x, y);
  2508. };
  2509. /**
  2510. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2511. */
  2512. Vector2.Lerp = function (start, end, amount) {
  2513. var x = start.x + ((end.x - start.x) * amount);
  2514. var y = start.y + ((end.y - start.y) * amount);
  2515. return new Vector2(x, y);
  2516. };
  2517. /**
  2518. * Returns the dot product (float) of the vector "left" and the vector "right".
  2519. */
  2520. Vector2.Dot = function (left, right) {
  2521. return left.x * right.x + left.y * right.y;
  2522. };
  2523. /**
  2524. * Returns a new Vector2 equal to the normalized passed vector.
  2525. */
  2526. Vector2.Normalize = function (vector) {
  2527. var newVector = vector.clone();
  2528. newVector.normalize();
  2529. return newVector;
  2530. };
  2531. /**
  2532. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2533. */
  2534. Vector2.Minimize = function (left, right) {
  2535. var x = (left.x < right.x) ? left.x : right.x;
  2536. var y = (left.y < right.y) ? left.y : right.y;
  2537. return new Vector2(x, y);
  2538. };
  2539. /**
  2540. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2541. */
  2542. Vector2.Maximize = function (left, right) {
  2543. var x = (left.x > right.x) ? left.x : right.x;
  2544. var y = (left.y > right.y) ? left.y : right.y;
  2545. return new Vector2(x, y);
  2546. };
  2547. /**
  2548. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2549. */
  2550. Vector2.Transform = function (vector, transformation) {
  2551. var r = Vector2.Zero();
  2552. Vector2.TransformToRef(vector, transformation, r);
  2553. return r;
  2554. };
  2555. /**
  2556. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2557. */
  2558. Vector2.TransformToRef = function (vector, transformation, result) {
  2559. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2560. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2561. result.x = x;
  2562. result.y = y;
  2563. };
  2564. /**
  2565. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2566. */
  2567. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2568. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2569. var sign = a < 0 ? -1 : 1;
  2570. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2571. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2572. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2573. };
  2574. /**
  2575. * Returns the distance (float) between the vectors "value1" and "value2".
  2576. */
  2577. Vector2.Distance = function (value1, value2) {
  2578. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2579. };
  2580. /**
  2581. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2582. */
  2583. Vector2.DistanceSquared = function (value1, value2) {
  2584. var x = value1.x - value2.x;
  2585. var y = value1.y - value2.y;
  2586. return (x * x) + (y * y);
  2587. };
  2588. /**
  2589. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2590. */
  2591. Vector2.Center = function (value1, value2) {
  2592. var center = value1.add(value2);
  2593. center.scaleInPlace(0.5);
  2594. return center;
  2595. };
  2596. /**
  2597. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2598. */
  2599. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2600. var l2 = Vector2.DistanceSquared(segA, segB);
  2601. if (l2 === 0.0) {
  2602. return Vector2.Distance(p, segA);
  2603. }
  2604. var v = segB.subtract(segA);
  2605. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2606. var proj = segA.add(v.multiplyByFloats(t, t));
  2607. return Vector2.Distance(p, proj);
  2608. };
  2609. return Vector2;
  2610. }());
  2611. BABYLON.Vector2 = Vector2;
  2612. /**
  2613. * Classed used to store (x,y,z) vector representation
  2614. * A Vector3 is the main object used in 3D geometry
  2615. * It can represent etiher the coordinates of a point the space, either a direction
  2616. * Reminder: Babylon.js uses a left handed forward facing system
  2617. */
  2618. var Vector3 = /** @class */ (function () {
  2619. /**
  2620. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2621. * @param x defines the first coordinates (on X axis)
  2622. * @param y defines the second coordinates (on Y axis)
  2623. * @param z defines the third coordinates (on Z axis)
  2624. */
  2625. function Vector3(
  2626. /**
  2627. * Defines the first coordinates (on X axis)
  2628. */
  2629. x,
  2630. /**
  2631. * Defines the second coordinates (on Y axis)
  2632. */
  2633. y,
  2634. /**
  2635. * Defines the third coordinates (on Z axis)
  2636. */
  2637. z) {
  2638. this.x = x;
  2639. this.y = y;
  2640. this.z = z;
  2641. }
  2642. /**
  2643. * Creates a string representation of the Vector3
  2644. * @returns a string with the Vector3 coordinates.
  2645. */
  2646. Vector3.prototype.toString = function () {
  2647. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2648. };
  2649. /**
  2650. * Gets the class name
  2651. * @returns the string "Vector3"
  2652. */
  2653. Vector3.prototype.getClassName = function () {
  2654. return "Vector3";
  2655. };
  2656. /**
  2657. * Creates the Vector3 hash code
  2658. * @returns a number which tends to be unique between Vector3 instances
  2659. */
  2660. Vector3.prototype.getHashCode = function () {
  2661. var hash = this.x || 0;
  2662. hash = (hash * 397) ^ (this.y || 0);
  2663. hash = (hash * 397) ^ (this.z || 0);
  2664. return hash;
  2665. };
  2666. // Operators
  2667. /**
  2668. * Creates an array containing three elements : the coordinates of the Vector3
  2669. * @returns a new array of numbers
  2670. */
  2671. Vector3.prototype.asArray = function () {
  2672. var result = [];
  2673. this.toArray(result, 0);
  2674. return result;
  2675. };
  2676. /**
  2677. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2678. * @param array defines the destination array
  2679. * @param index defines the offset in the destination array
  2680. * @returns the current Vector3
  2681. */
  2682. Vector3.prototype.toArray = function (array, index) {
  2683. if (index === void 0) { index = 0; }
  2684. array[index] = this.x;
  2685. array[index + 1] = this.y;
  2686. array[index + 2] = this.z;
  2687. return this;
  2688. };
  2689. /**
  2690. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2691. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2692. */
  2693. Vector3.prototype.toQuaternion = function () {
  2694. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2695. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2696. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2697. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2698. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2699. var cosy = Math.cos(this.y * 0.5);
  2700. var siny = Math.sin(this.y * 0.5);
  2701. result.x = coszMinusx * siny;
  2702. result.y = -sinzMinusx * siny;
  2703. result.z = sinxPlusz * cosy;
  2704. result.w = cosxPlusz * cosy;
  2705. return result;
  2706. };
  2707. /**
  2708. * Adds the passed vector to the current Vector3
  2709. * @param otherVector defines the second operand
  2710. * @returns the current updated Vector3
  2711. */
  2712. Vector3.prototype.addInPlace = function (otherVector) {
  2713. this.x += otherVector.x;
  2714. this.y += otherVector.y;
  2715. this.z += otherVector.z;
  2716. return this;
  2717. };
  2718. /**
  2719. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2720. * @param otherVector defines the second operand
  2721. * @returns the resulting Vector3
  2722. */
  2723. Vector3.prototype.add = function (otherVector) {
  2724. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2725. };
  2726. /**
  2727. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2728. * @param otherVector defines the second operand
  2729. * @param result defines the Vector3 object where to store the result
  2730. * @returns the current Vector3
  2731. */
  2732. Vector3.prototype.addToRef = function (otherVector, result) {
  2733. result.x = this.x + otherVector.x;
  2734. result.y = this.y + otherVector.y;
  2735. result.z = this.z + otherVector.z;
  2736. return this;
  2737. };
  2738. /**
  2739. * Subtract the passed vector from the current Vector3
  2740. * @param otherVector defines the second operand
  2741. * @returns the current updated Vector3
  2742. */
  2743. Vector3.prototype.subtractInPlace = function (otherVector) {
  2744. this.x -= otherVector.x;
  2745. this.y -= otherVector.y;
  2746. this.z -= otherVector.z;
  2747. return this;
  2748. };
  2749. /**
  2750. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2751. * @param otherVector defines the second operand
  2752. * @returns the resulting Vector3
  2753. */
  2754. Vector3.prototype.subtract = function (otherVector) {
  2755. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2756. };
  2757. /**
  2758. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2759. * @param otherVector defines the second operand
  2760. * @param result defines the Vector3 object where to store the result
  2761. * @returns the current Vector3
  2762. */
  2763. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2764. result.x = this.x - otherVector.x;
  2765. result.y = this.y - otherVector.y;
  2766. result.z = this.z - otherVector.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2771. * @param x defines the x coordinate of the operand
  2772. * @param y defines the y coordinate of the operand
  2773. * @param z defines the z coordinate of the operand
  2774. * @returns the resulting Vector3
  2775. */
  2776. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2777. return new Vector3(this.x - x, this.y - y, this.z - z);
  2778. };
  2779. /**
  2780. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2781. * @param x defines the x coordinate of the operand
  2782. * @param y defines the y coordinate of the operand
  2783. * @param z defines the z coordinate of the operand
  2784. * @param result defines the Vector3 object where to store the result
  2785. * @returns the current Vector3
  2786. */
  2787. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2788. result.x = this.x - x;
  2789. result.y = this.y - y;
  2790. result.z = this.z - z;
  2791. return this;
  2792. };
  2793. /**
  2794. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2795. * @returns a new Vector3
  2796. */
  2797. Vector3.prototype.negate = function () {
  2798. return new Vector3(-this.x, -this.y, -this.z);
  2799. };
  2800. /**
  2801. * Multiplies the Vector3 coordinates by the float "scale"
  2802. * @param scale defines the multiplier factor
  2803. * @returns the current updated Vector3
  2804. */
  2805. Vector3.prototype.scaleInPlace = function (scale) {
  2806. this.x *= scale;
  2807. this.y *= scale;
  2808. this.z *= scale;
  2809. return this;
  2810. };
  2811. /**
  2812. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2813. * @param scale defines the multiplier factor
  2814. * @returns a new Vector3
  2815. */
  2816. Vector3.prototype.scale = function (scale) {
  2817. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2818. };
  2819. /**
  2820. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2821. * @param scale defines the multiplier factor
  2822. * @param result defines the Vector3 object where to store the result
  2823. * @returns the current Vector3
  2824. */
  2825. Vector3.prototype.scaleToRef = function (scale, result) {
  2826. result.x = this.x * scale;
  2827. result.y = this.y * scale;
  2828. result.z = this.z * scale;
  2829. return this;
  2830. };
  2831. /**
  2832. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2833. * @param otherVector defines the second operand
  2834. * @returns true if both vectors are equals
  2835. */
  2836. Vector3.prototype.equals = function (otherVector) {
  2837. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2838. };
  2839. /**
  2840. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2841. * @param otherVector defines the second operand
  2842. * @param epsilon defines the minimal distance to define values as equals
  2843. * @returns true if both vectors are distant less than epsilon
  2844. */
  2845. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2846. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2847. 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);
  2848. };
  2849. /**
  2850. * Returns true if the current Vector3 coordinates equals the passed floats
  2851. * @param x defines the x coordinate of the operand
  2852. * @param y defines the y coordinate of the operand
  2853. * @param z defines the z coordinate of the operand
  2854. * @returns true if both vectors are equals
  2855. */
  2856. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2857. return this.x === x && this.y === y && this.z === z;
  2858. };
  2859. /**
  2860. * Multiplies the current Vector3 coordinates by the passed ones
  2861. * @param otherVector defines the second operand
  2862. * @returns the current updated Vector3
  2863. */
  2864. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2865. this.x *= otherVector.x;
  2866. this.y *= otherVector.y;
  2867. this.z *= otherVector.z;
  2868. return this;
  2869. };
  2870. /**
  2871. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2872. * @param otherVector defines the second operand
  2873. * @returns the new Vector3
  2874. */
  2875. Vector3.prototype.multiply = function (otherVector) {
  2876. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2877. };
  2878. /**
  2879. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2880. * @param otherVector defines the second operand
  2881. * @param result defines the Vector3 object where to store the result
  2882. * @returns the current Vector3
  2883. */
  2884. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2885. result.x = this.x * otherVector.x;
  2886. result.y = this.y * otherVector.y;
  2887. result.z = this.z * otherVector.z;
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2892. * @param x defines the x coordinate of the operand
  2893. * @param y defines the y coordinate of the operand
  2894. * @param z defines the z coordinate of the operand
  2895. * @returns the new Vector3
  2896. */
  2897. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2898. return new Vector3(this.x * x, this.y * y, this.z * z);
  2899. };
  2900. /**
  2901. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2902. * @param otherVector defines the second operand
  2903. * @returns the new Vector3
  2904. */
  2905. Vector3.prototype.divide = function (otherVector) {
  2906. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2907. };
  2908. /**
  2909. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2910. * @param otherVector defines the second operand
  2911. * @param result defines the Vector3 object where to store the result
  2912. * @returns the current Vector3
  2913. */
  2914. Vector3.prototype.divideToRef = function (otherVector, result) {
  2915. result.x = this.x / otherVector.x;
  2916. result.y = this.y / otherVector.y;
  2917. result.z = this.z / otherVector.z;
  2918. return this;
  2919. };
  2920. /**
  2921. * Divides the current Vector3 coordinates by the passed ones.
  2922. * @param otherVector defines the second operand
  2923. * @returns the current updated Vector3
  2924. */
  2925. Vector3.prototype.divideInPlace = function (otherVector) {
  2926. return this.divideToRef(otherVector, this);
  2927. };
  2928. /**
  2929. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2930. * @param other defines the second operand
  2931. * @returns the current updated Vector3
  2932. */
  2933. Vector3.prototype.minimizeInPlace = function (other) {
  2934. if (other.x < this.x)
  2935. this.x = other.x;
  2936. if (other.y < this.y)
  2937. this.y = other.y;
  2938. if (other.z < this.z)
  2939. this.z = other.z;
  2940. return this;
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.maximizeInPlace = function (other) {
  2948. if (other.x > this.x)
  2949. this.x = other.x;
  2950. if (other.y > this.y)
  2951. this.y = other.y;
  2952. if (other.z > this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2957. /**
  2958. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2959. */
  2960. get: function () {
  2961. var absX = Math.abs(this.x);
  2962. var absY = Math.abs(this.y);
  2963. if (absX !== absY) {
  2964. return true;
  2965. }
  2966. var absZ = Math.abs(this.z);
  2967. if (absX !== absZ) {
  2968. return true;
  2969. }
  2970. if (absY !== absZ) {
  2971. return true;
  2972. }
  2973. return false;
  2974. },
  2975. enumerable: true,
  2976. configurable: true
  2977. });
  2978. // Properties
  2979. /**
  2980. * Gets the length of the Vector3
  2981. * @returns the length of the Vecto3
  2982. */
  2983. Vector3.prototype.length = function () {
  2984. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2985. };
  2986. /**
  2987. * Gets the squared length of the Vector3
  2988. * @returns squared length of the Vector3
  2989. */
  2990. Vector3.prototype.lengthSquared = function () {
  2991. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2992. };
  2993. /**
  2994. * Normalize the current Vector3.
  2995. * Please note that this is an in place operation.
  2996. * @returns the current updated Vector3
  2997. */
  2998. Vector3.prototype.normalize = function () {
  2999. var len = this.length();
  3000. if (len === 0 || len === 1.0)
  3001. return this;
  3002. var num = 1.0 / len;
  3003. this.x *= num;
  3004. this.y *= num;
  3005. this.z *= num;
  3006. return this;
  3007. };
  3008. /**
  3009. * Normalize the current Vector3 to a new vector
  3010. * @returns the new Vector3
  3011. */
  3012. Vector3.prototype.normalizeToNew = function () {
  3013. var normalized = new Vector3(0, 0, 0);
  3014. this.normalizeToRef(normalized);
  3015. return normalized;
  3016. };
  3017. /**
  3018. * Normalize the current Vector3 to the reference
  3019. * @param reference define the Vector3 to update
  3020. * @returns the updated Vector3
  3021. */
  3022. Vector3.prototype.normalizeToRef = function (reference) {
  3023. var len = this.length();
  3024. if (len === 0 || len === 1.0) {
  3025. reference.set(this.x, this.y, this.z);
  3026. return reference;
  3027. }
  3028. var scale = 1.0 / len;
  3029. this.scaleToRef(scale, reference);
  3030. return reference;
  3031. };
  3032. /**
  3033. * Creates a new Vector3 copied from the current Vector3
  3034. * @returns the new Vector3
  3035. */
  3036. Vector3.prototype.clone = function () {
  3037. return new Vector3(this.x, this.y, this.z);
  3038. };
  3039. /**
  3040. * Copies the passed vector coordinates to the current Vector3 ones
  3041. * @param source defines the source Vector3
  3042. * @returns the current updated Vector3
  3043. */
  3044. Vector3.prototype.copyFrom = function (source) {
  3045. this.x = source.x;
  3046. this.y = source.y;
  3047. this.z = source.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Copies the passed floats to the current Vector3 coordinates
  3052. * @param x defines the x coordinate of the operand
  3053. * @param y defines the y coordinate of the operand
  3054. * @param z defines the z coordinate of the operand
  3055. * @returns the current updated Vector3
  3056. */
  3057. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3058. this.x = x;
  3059. this.y = y;
  3060. this.z = z;
  3061. return this;
  3062. };
  3063. /**
  3064. * Copies the passed floats to the current Vector3 coordinates
  3065. * @param x defines the x coordinate of the operand
  3066. * @param y defines the y coordinate of the operand
  3067. * @param z defines the z coordinate of the operand
  3068. * @returns the current updated Vector3
  3069. */
  3070. Vector3.prototype.set = function (x, y, z) {
  3071. return this.copyFromFloats(x, y, z);
  3072. };
  3073. // Statics
  3074. /**
  3075. * Get the clip factor between two vectors
  3076. * @param vector0 defines the first operand
  3077. * @param vector1 defines the second operand
  3078. * @param axis defines the axis to use
  3079. * @param size defines the size along the axis
  3080. * @returns the clip factor
  3081. */
  3082. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3083. var d0 = Vector3.Dot(vector0, axis) - size;
  3084. var d1 = Vector3.Dot(vector1, axis) - size;
  3085. var s = d0 / (d0 - d1);
  3086. return s;
  3087. };
  3088. /**
  3089. * Get angle between two vectors
  3090. * @param vector0 angle between vector0 and vector1
  3091. * @param vector1 angle between vector0 and vector1
  3092. * @param normal direction of the normal
  3093. * @return the angle between vector0 and vector1
  3094. */
  3095. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3096. var v0 = vector0.clone().normalize();
  3097. var v1 = vector1.clone().normalize();
  3098. var dot = Vector3.Dot(v0, v1);
  3099. var n = Vector3.Cross(v0, v1);
  3100. if (Vector3.Dot(n, normal) > 0) {
  3101. return Math.acos(dot);
  3102. }
  3103. return -Math.acos(dot);
  3104. };
  3105. /**
  3106. * Returns a new Vector3 set from the index "offset" of the passed array
  3107. * @param array defines the source array
  3108. * @param offset defines the offset in the source array
  3109. * @returns the new Vector3
  3110. */
  3111. Vector3.FromArray = function (array, offset) {
  3112. if (!offset) {
  3113. offset = 0;
  3114. }
  3115. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3119. * This function is deprecated. Use FromArray instead
  3120. * @param array defines the source array
  3121. * @param offset defines the offset in the source array
  3122. * @returns the new Vector3
  3123. */
  3124. Vector3.FromFloatArray = function (array, offset) {
  3125. return Vector3.FromArray(array, offset);
  3126. };
  3127. /**
  3128. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3129. * @param array defines the source array
  3130. * @param offset defines the offset in the source array
  3131. * @param result defines the Vector3 where to store the result
  3132. */
  3133. Vector3.FromArrayToRef = function (array, offset, result) {
  3134. result.x = array[offset];
  3135. result.y = array[offset + 1];
  3136. result.z = array[offset + 2];
  3137. };
  3138. /**
  3139. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3140. * This function is deprecated. Use FromArrayToRef instead.
  3141. * @param array defines the source array
  3142. * @param offset defines the offset in the source array
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3146. return Vector3.FromArrayToRef(array, offset, result);
  3147. };
  3148. /**
  3149. * Sets the passed vector "result" with the passed floats.
  3150. * @param x defines the x coordinate of the source
  3151. * @param y defines the y coordinate of the source
  3152. * @param z defines the z coordinate of the source
  3153. * @param result defines the Vector3 where to store the result
  3154. */
  3155. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3156. result.x = x;
  3157. result.y = y;
  3158. result.z = z;
  3159. };
  3160. /**
  3161. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3162. * @returns a new empty Vector3
  3163. */
  3164. Vector3.Zero = function () {
  3165. return new Vector3(0.0, 0.0, 0.0);
  3166. };
  3167. /**
  3168. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3169. * @returns a new unit Vector3
  3170. */
  3171. Vector3.One = function () {
  3172. return new Vector3(1.0, 1.0, 1.0);
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3176. * @returns a new up Vector3
  3177. */
  3178. Vector3.Up = function () {
  3179. return new Vector3(0.0, 1.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3183. * @returns a new forward Vector3
  3184. */
  3185. Vector3.Forward = function () {
  3186. return new Vector3(0.0, 0.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3190. * @returns a new right Vector3
  3191. */
  3192. Vector3.Right = function () {
  3193. return new Vector3(1.0, 0.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3197. * @returns a new left Vector3
  3198. */
  3199. Vector3.Left = function () {
  3200. return new Vector3(-1.0, 0.0, 0.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3204. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3205. * @param vector defines the Vector3 to transform
  3206. * @param transformation defines the transformation matrix
  3207. * @returns the transformed Vector3
  3208. */
  3209. Vector3.TransformCoordinates = function (vector, transformation) {
  3210. var result = Vector3.Zero();
  3211. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3212. return result;
  3213. };
  3214. /**
  3215. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3216. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3217. * @param vector defines the Vector3 to transform
  3218. * @param transformation defines the transformation matrix
  3219. * @param result defines the Vector3 where to store the result
  3220. */
  3221. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3222. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3223. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3224. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3225. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3226. result.x = x / w;
  3227. result.y = y / w;
  3228. result.z = z / w;
  3229. };
  3230. /**
  3231. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3232. * This method computes tranformed coordinates only, not transformed direction vectors
  3233. * @param x define the x coordinate of the source vector
  3234. * @param y define the y coordinate of the source vector
  3235. * @param z define the z coordinate of the source vector
  3236. * @param transformation defines the transformation matrix
  3237. * @param result defines the Vector3 where to store the result
  3238. */
  3239. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3240. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3241. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3242. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3243. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3244. result.x = rx / rw;
  3245. result.y = ry / rw;
  3246. result.z = rz / rw;
  3247. };
  3248. /**
  3249. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3250. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3251. * @param vector defines the Vector3 to transform
  3252. * @param transformation defines the transformation matrix
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.TransformNormal = function (vector, transformation) {
  3256. var result = Vector3.Zero();
  3257. Vector3.TransformNormalToRef(vector, transformation, result);
  3258. return result;
  3259. };
  3260. /**
  3261. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3262. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3263. * @param vector defines the Vector3 to transform
  3264. * @param transformation defines the transformation matrix
  3265. * @param result defines the Vector3 where to store the result
  3266. */
  3267. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3268. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3269. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3270. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3271. result.x = x;
  3272. result.y = y;
  3273. result.z = z;
  3274. };
  3275. /**
  3276. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3277. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3278. * @param x define the x coordinate of the source vector
  3279. * @param y define the y coordinate of the source vector
  3280. * @param z define the z coordinate of the source vector
  3281. * @param transformation defines the transformation matrix
  3282. * @param result defines the Vector3 where to store the result
  3283. */
  3284. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3285. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3286. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3287. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3291. * @param value1 defines the first control point
  3292. * @param value2 defines the second control point
  3293. * @param value3 defines the third control point
  3294. * @param value4 defines the fourth control point
  3295. * @param amount defines the amount on the spline to use
  3296. * @returns the new Vector3
  3297. */
  3298. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3299. var squared = amount * amount;
  3300. var cubed = amount * squared;
  3301. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3302. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3303. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3304. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3305. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3306. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3307. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3308. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3309. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3310. return new Vector3(x, y, z);
  3311. };
  3312. /**
  3313. * 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"
  3314. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3315. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3316. * @param value defines the current value
  3317. * @param min defines the lower range value
  3318. * @param max defines the upper range value
  3319. * @returns the new Vector3
  3320. */
  3321. Vector3.Clamp = function (value, min, max) {
  3322. var x = value.x;
  3323. x = (x > max.x) ? max.x : x;
  3324. x = (x < min.x) ? min.x : x;
  3325. var y = value.y;
  3326. y = (y > max.y) ? max.y : y;
  3327. y = (y < min.y) ? min.y : y;
  3328. var z = value.z;
  3329. z = (z > max.z) ? max.z : z;
  3330. z = (z < min.z) ? min.z : z;
  3331. return new Vector3(x, y, z);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3335. * @param value1 defines the first control point
  3336. * @param tangent1 defines the first tangent vector
  3337. * @param value2 defines the second control point
  3338. * @param tangent2 defines the second tangent vector
  3339. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3340. * @returns the new Vector3
  3341. */
  3342. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3343. var squared = amount * amount;
  3344. var cubed = amount * squared;
  3345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3347. var part3 = (cubed - (2.0 * squared)) + amount;
  3348. var part4 = cubed - squared;
  3349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3351. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3352. return new Vector3(x, y, z);
  3353. };
  3354. /**
  3355. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3356. * @param start defines the start value
  3357. * @param end defines the end value
  3358. * @param amount max defines amount between both (between 0 and 1)
  3359. * @returns the new Vector3
  3360. */
  3361. Vector3.Lerp = function (start, end, amount) {
  3362. var result = new Vector3(0, 0, 0);
  3363. Vector3.LerpToRef(start, end, amount, result);
  3364. return result;
  3365. };
  3366. /**
  3367. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3368. * @param start defines the start value
  3369. * @param end defines the end value
  3370. * @param amount max defines amount between both (between 0 and 1)
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.LerpToRef = function (start, end, amount, result) {
  3374. result.x = start.x + ((end.x - start.x) * amount);
  3375. result.y = start.y + ((end.y - start.y) * amount);
  3376. result.z = start.z + ((end.z - start.z) * amount);
  3377. };
  3378. /**
  3379. * Returns the dot product (float) between the vectors "left" and "right"
  3380. * @param left defines the left operand
  3381. * @param right defines the right operand
  3382. * @returns the dot product
  3383. */
  3384. Vector3.Dot = function (left, right) {
  3385. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3386. };
  3387. /**
  3388. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3389. * The cross product is then orthogonal to both "left" and "right"
  3390. * @param left defines the left operand
  3391. * @param right defines the right operand
  3392. * @returns the cross product
  3393. */
  3394. Vector3.Cross = function (left, right) {
  3395. var result = Vector3.Zero();
  3396. Vector3.CrossToRef(left, right, result);
  3397. return result;
  3398. };
  3399. /**
  3400. * Sets the passed vector "result" with the cross product of "left" and "right"
  3401. * The cross product is then orthogonal to both "left" and "right"
  3402. * @param left defines the left operand
  3403. * @param right defines the right operand
  3404. * @param result defines the Vector3 where to store the result
  3405. */
  3406. Vector3.CrossToRef = function (left, right, result) {
  3407. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3408. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3409. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3410. result.copyFrom(MathTmp.Vector3[0]);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 as the normalization of the passed vector
  3414. * @param vector defines the Vector3 to normalize
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.Normalize = function (vector) {
  3418. var result = Vector3.Zero();
  3419. Vector3.NormalizeToRef(vector, result);
  3420. return result;
  3421. };
  3422. /**
  3423. * Sets the passed vector "result" with the normalization of the passed first vector
  3424. * @param vector defines the Vector3 to normalize
  3425. * @param result defines the Vector3 where to store the result
  3426. */
  3427. Vector3.NormalizeToRef = function (vector, result) {
  3428. result.copyFrom(vector);
  3429. result.normalize();
  3430. };
  3431. /**
  3432. * Project a Vector3 onto screen space
  3433. * @param vector defines the Vector3 to project
  3434. * @param world defines the world matrix to use
  3435. * @param transform defines the transform (view x projection) matrix to use
  3436. * @param viewport defines the screen viewport to use
  3437. * @returns the new Vector3
  3438. */
  3439. Vector3.Project = function (vector, world, transform, viewport) {
  3440. var cw = viewport.width;
  3441. var ch = viewport.height;
  3442. var cx = viewport.x;
  3443. var cy = viewport.y;
  3444. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3445. 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);
  3446. var matrix = MathTmp.Matrix[0];
  3447. world.multiplyToRef(transform, matrix);
  3448. matrix.multiplyToRef(viewportMatrix, matrix);
  3449. return Vector3.TransformCoordinates(vector, matrix);
  3450. };
  3451. /**
  3452. * Unproject from screen space to object space
  3453. * @param source defines the screen space Vector3 to use
  3454. * @param viewportWidth defines the current width of the viewport
  3455. * @param viewportHeight defines the current height of the viewport
  3456. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3457. * @param transform defines the transform (view x projection) matrix to use
  3458. * @returns the new Vector3
  3459. */
  3460. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3461. var matrix = MathTmp.Matrix[0];
  3462. world.multiplyToRef(transform, matrix);
  3463. matrix.invert();
  3464. source.x = source.x / viewportWidth * 2 - 1;
  3465. source.y = -(source.y / viewportHeight * 2 - 1);
  3466. var vector = Vector3.TransformCoordinates(source, matrix);
  3467. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3468. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3469. vector = vector.scale(1.0 / num);
  3470. }
  3471. return vector;
  3472. };
  3473. /**
  3474. * Unproject from screen space to object space
  3475. * @param source defines the screen space Vector3 to use
  3476. * @param viewportWidth defines the current width of the viewport
  3477. * @param viewportHeight defines the current height of the viewport
  3478. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3479. * @param view defines the view matrix to use
  3480. * @param projection defines the projection matrix to use
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3484. var result = Vector3.Zero();
  3485. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3486. return result;
  3487. };
  3488. /**
  3489. * Unproject from screen space to object space
  3490. * @param source defines the screen space Vector3 to use
  3491. * @param viewportWidth defines the current width of the viewport
  3492. * @param viewportHeight defines the current height of the viewport
  3493. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3494. * @param view defines the view matrix to use
  3495. * @param projection defines the projection matrix to use
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3499. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3500. };
  3501. /**
  3502. * Unproject from screen space to object space
  3503. * @param sourceX defines the screen space x coordinate to use
  3504. * @param sourceY defines the screen space y coordinate to use
  3505. * @param sourceZ defines the screen space z coordinate to use
  3506. * @param viewportWidth defines the current width of the viewport
  3507. * @param viewportHeight defines the current height of the viewport
  3508. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3509. * @param view defines the view matrix to use
  3510. * @param projection defines the projection matrix to use
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3514. var matrix = MathTmp.Matrix[0];
  3515. world.multiplyToRef(view, matrix);
  3516. matrix.multiplyToRef(projection, matrix);
  3517. matrix.invert();
  3518. var screenSource = MathTmp.Vector3[0];
  3519. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3520. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3521. screenSource.z = 2 * sourceZ - 1.0;
  3522. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3523. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3524. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3525. result.scaleInPlace(1.0 / num);
  3526. }
  3527. };
  3528. /**
  3529. * Gets the minimal coordinate values between two Vector3
  3530. * @param left defines the first operand
  3531. * @param right defines the second operand
  3532. * @returns the new Vector3
  3533. */
  3534. Vector3.Minimize = function (left, right) {
  3535. var min = left.clone();
  3536. min.minimizeInPlace(right);
  3537. return min;
  3538. };
  3539. /**
  3540. * Gets the maximal coordinate values between two Vector3
  3541. * @param left defines the first operand
  3542. * @param right defines the second operand
  3543. * @returns the new Vector3
  3544. */
  3545. Vector3.Maximize = function (left, right) {
  3546. var max = left.clone();
  3547. max.maximizeInPlace(right);
  3548. return max;
  3549. };
  3550. /**
  3551. * Returns the distance between the vectors "value1" and "value2"
  3552. * @param value1 defines the first operand
  3553. * @param value2 defines the second operand
  3554. * @returns the distance
  3555. */
  3556. Vector3.Distance = function (value1, value2) {
  3557. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3558. };
  3559. /**
  3560. * Returns the squared distance between the vectors "value1" and "value2"
  3561. * @param value1 defines the first operand
  3562. * @param value2 defines the second operand
  3563. * @returns the squared distance
  3564. */
  3565. Vector3.DistanceSquared = function (value1, value2) {
  3566. var x = value1.x - value2.x;
  3567. var y = value1.y - value2.y;
  3568. var z = value1.z - value2.z;
  3569. return (x * x) + (y * y) + (z * z);
  3570. };
  3571. /**
  3572. * Returns a new Vector3 located at the center between "value1" and "value2"
  3573. * @param value1 defines the first operand
  3574. * @param value2 defines the second operand
  3575. * @returns the new Vector3
  3576. */
  3577. Vector3.Center = function (value1, value2) {
  3578. var center = value1.add(value2);
  3579. center.scaleInPlace(0.5);
  3580. return center;
  3581. };
  3582. /**
  3583. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3584. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3585. * to something in order to rotate it from its local system to the given target system
  3586. * Note: axis1, axis2 and axis3 are normalized during this operation
  3587. * @param axis1 defines the first axis
  3588. * @param axis2 defines the second axis
  3589. * @param axis3 defines the third axis
  3590. * @returns a new Vector3
  3591. */
  3592. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3593. var rotation = Vector3.Zero();
  3594. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3595. return rotation;
  3596. };
  3597. /**
  3598. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3599. * @param axis1 defines the first axis
  3600. * @param axis2 defines the second axis
  3601. * @param axis3 defines the third axis
  3602. * @param ref defines the Vector3 where to store the result
  3603. */
  3604. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3605. var quat = MathTmp.Quaternion[0];
  3606. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3607. quat.toEulerAnglesToRef(ref);
  3608. };
  3609. return Vector3;
  3610. }());
  3611. BABYLON.Vector3 = Vector3;
  3612. //Vector4 class created for EulerAngle class conversion to Quaternion
  3613. var Vector4 = /** @class */ (function () {
  3614. /**
  3615. * Creates a Vector4 object from the passed floats.
  3616. */
  3617. function Vector4(x, y, z, w) {
  3618. this.x = x;
  3619. this.y = y;
  3620. this.z = z;
  3621. this.w = w;
  3622. }
  3623. /**
  3624. * Returns the string with the Vector4 coordinates.
  3625. */
  3626. Vector4.prototype.toString = function () {
  3627. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3628. };
  3629. /**
  3630. * Returns the string "Vector4".
  3631. */
  3632. Vector4.prototype.getClassName = function () {
  3633. return "Vector4";
  3634. };
  3635. /**
  3636. * Returns the Vector4 hash code.
  3637. */
  3638. Vector4.prototype.getHashCode = function () {
  3639. var hash = this.x || 0;
  3640. hash = (hash * 397) ^ (this.y || 0);
  3641. hash = (hash * 397) ^ (this.z || 0);
  3642. hash = (hash * 397) ^ (this.w || 0);
  3643. return hash;
  3644. };
  3645. // Operators
  3646. /**
  3647. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3648. */
  3649. Vector4.prototype.asArray = function () {
  3650. var result = new Array();
  3651. this.toArray(result, 0);
  3652. return result;
  3653. };
  3654. /**
  3655. * Populates the passed array from the passed index with the Vector4 coordinates.
  3656. * Returns the Vector4.
  3657. */
  3658. Vector4.prototype.toArray = function (array, index) {
  3659. if (index === undefined) {
  3660. index = 0;
  3661. }
  3662. array[index] = this.x;
  3663. array[index + 1] = this.y;
  3664. array[index + 2] = this.z;
  3665. array[index + 3] = this.w;
  3666. return this;
  3667. };
  3668. /**
  3669. * Adds the passed vector to the current Vector4.
  3670. * Returns the updated Vector4.
  3671. */
  3672. Vector4.prototype.addInPlace = function (otherVector) {
  3673. this.x += otherVector.x;
  3674. this.y += otherVector.y;
  3675. this.z += otherVector.z;
  3676. this.w += otherVector.w;
  3677. return this;
  3678. };
  3679. /**
  3680. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3681. */
  3682. Vector4.prototype.add = function (otherVector) {
  3683. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3684. };
  3685. /**
  3686. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3687. * Returns the current Vector4.
  3688. */
  3689. Vector4.prototype.addToRef = function (otherVector, result) {
  3690. result.x = this.x + otherVector.x;
  3691. result.y = this.y + otherVector.y;
  3692. result.z = this.z + otherVector.z;
  3693. result.w = this.w + otherVector.w;
  3694. return this;
  3695. };
  3696. /**
  3697. * Subtract in place the passed vector from the current Vector4.
  3698. * Returns the updated Vector4.
  3699. */
  3700. Vector4.prototype.subtractInPlace = function (otherVector) {
  3701. this.x -= otherVector.x;
  3702. this.y -= otherVector.y;
  3703. this.z -= otherVector.z;
  3704. this.w -= otherVector.w;
  3705. return this;
  3706. };
  3707. /**
  3708. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3709. */
  3710. Vector4.prototype.subtract = function (otherVector) {
  3711. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3712. };
  3713. /**
  3714. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3715. * Returns the current Vector4.
  3716. */
  3717. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3718. result.x = this.x - otherVector.x;
  3719. result.y = this.y - otherVector.y;
  3720. result.z = this.z - otherVector.z;
  3721. result.w = this.w - otherVector.w;
  3722. return this;
  3723. };
  3724. /**
  3725. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3726. */
  3727. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3728. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3729. };
  3730. /**
  3731. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3732. * Returns the current Vector4.
  3733. */
  3734. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3735. result.x = this.x - x;
  3736. result.y = this.y - y;
  3737. result.z = this.z - z;
  3738. result.w = this.w - w;
  3739. return this;
  3740. };
  3741. /**
  3742. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3743. */
  3744. Vector4.prototype.negate = function () {
  3745. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3746. };
  3747. /**
  3748. * Multiplies the current Vector4 coordinates by scale (float).
  3749. * Returns the updated Vector4.
  3750. */
  3751. Vector4.prototype.scaleInPlace = function (scale) {
  3752. this.x *= scale;
  3753. this.y *= scale;
  3754. this.z *= scale;
  3755. this.w *= scale;
  3756. return this;
  3757. };
  3758. /**
  3759. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3760. */
  3761. Vector4.prototype.scale = function (scale) {
  3762. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3763. };
  3764. /**
  3765. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3766. * Returns the current Vector4.
  3767. */
  3768. Vector4.prototype.scaleToRef = function (scale, result) {
  3769. result.x = this.x * scale;
  3770. result.y = this.y * scale;
  3771. result.z = this.z * scale;
  3772. result.w = this.w * scale;
  3773. return this;
  3774. };
  3775. /**
  3776. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3777. */
  3778. Vector4.prototype.equals = function (otherVector) {
  3779. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3780. };
  3781. /**
  3782. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3783. */
  3784. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3785. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3786. return otherVector
  3787. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3788. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3789. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3790. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3791. };
  3792. /**
  3793. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3794. */
  3795. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3796. return this.x === x && this.y === y && this.z === z && this.w === w;
  3797. };
  3798. /**
  3799. * Multiplies in place the current Vector4 by the passed one.
  3800. * Returns the updated Vector4.
  3801. */
  3802. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3803. this.x *= otherVector.x;
  3804. this.y *= otherVector.y;
  3805. this.z *= otherVector.z;
  3806. this.w *= otherVector.w;
  3807. return this;
  3808. };
  3809. /**
  3810. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3811. */
  3812. Vector4.prototype.multiply = function (otherVector) {
  3813. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3814. };
  3815. /**
  3816. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3817. * Returns the current Vector4.
  3818. */
  3819. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3820. result.x = this.x * otherVector.x;
  3821. result.y = this.y * otherVector.y;
  3822. result.z = this.z * otherVector.z;
  3823. result.w = this.w * otherVector.w;
  3824. return this;
  3825. };
  3826. /**
  3827. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3828. */
  3829. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3830. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3831. };
  3832. /**
  3833. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3834. */
  3835. Vector4.prototype.divide = function (otherVector) {
  3836. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3837. };
  3838. /**
  3839. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3840. * Returns the current Vector4.
  3841. */
  3842. Vector4.prototype.divideToRef = function (otherVector, result) {
  3843. result.x = this.x / otherVector.x;
  3844. result.y = this.y / otherVector.y;
  3845. result.z = this.z / otherVector.z;
  3846. result.w = this.w / otherVector.w;
  3847. return this;
  3848. };
  3849. /**
  3850. * Divides the current Vector3 coordinates by the passed ones.
  3851. * @returns the updated Vector3.
  3852. */
  3853. Vector4.prototype.divideInPlace = function (otherVector) {
  3854. return this.divideToRef(otherVector, this);
  3855. };
  3856. /**
  3857. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3858. * @param other defines the second operand
  3859. * @returns the current updated Vector4
  3860. */
  3861. Vector4.prototype.minimizeInPlace = function (other) {
  3862. if (other.x < this.x)
  3863. this.x = other.x;
  3864. if (other.y < this.y)
  3865. this.y = other.y;
  3866. if (other.z < this.z)
  3867. this.z = other.z;
  3868. if (other.w < this.w)
  3869. this.w = other.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3874. * @param other defines the second operand
  3875. * @returns the current updated Vector4
  3876. */
  3877. Vector4.prototype.maximizeInPlace = function (other) {
  3878. if (other.x > this.x)
  3879. this.x = other.x;
  3880. if (other.y > this.y)
  3881. this.y = other.y;
  3882. if (other.z > this.z)
  3883. this.z = other.z;
  3884. if (other.w > this.w)
  3885. this.w = other.w;
  3886. return this;
  3887. };
  3888. // Properties
  3889. /**
  3890. * Returns the Vector4 length (float).
  3891. */
  3892. Vector4.prototype.length = function () {
  3893. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3894. };
  3895. /**
  3896. * Returns the Vector4 squared length (float).
  3897. */
  3898. Vector4.prototype.lengthSquared = function () {
  3899. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3900. };
  3901. // Methods
  3902. /**
  3903. * Normalizes in place the Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.normalize = function () {
  3907. var len = this.length();
  3908. if (len === 0)
  3909. return this;
  3910. var num = 1.0 / len;
  3911. this.x *= num;
  3912. this.y *= num;
  3913. this.z *= num;
  3914. this.w *= num;
  3915. return this;
  3916. };
  3917. /**
  3918. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3919. */
  3920. Vector4.prototype.toVector3 = function () {
  3921. return new Vector3(this.x, this.y, this.z);
  3922. };
  3923. /**
  3924. * Returns a new Vector4 copied from the current one.
  3925. */
  3926. Vector4.prototype.clone = function () {
  3927. return new Vector4(this.x, this.y, this.z, this.w);
  3928. };
  3929. /**
  3930. * Updates the current Vector4 with the passed one coordinates.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.copyFrom = function (source) {
  3934. this.x = source.x;
  3935. this.y = source.y;
  3936. this.z = source.z;
  3937. this.w = source.w;
  3938. return this;
  3939. };
  3940. /**
  3941. * Updates the current Vector4 coordinates with the passed floats.
  3942. * Returns the updated Vector4.
  3943. */
  3944. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3945. this.x = x;
  3946. this.y = y;
  3947. this.z = z;
  3948. this.w = w;
  3949. return this;
  3950. };
  3951. /**
  3952. * Updates the current Vector4 coordinates with the passed floats.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.set = function (x, y, z, w) {
  3956. return this.copyFromFloats(x, y, z, w);
  3957. };
  3958. // Statics
  3959. /**
  3960. * Returns a new Vector4 set from the starting index of the passed array.
  3961. */
  3962. Vector4.FromArray = function (array, offset) {
  3963. if (!offset) {
  3964. offset = 0;
  3965. }
  3966. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3967. };
  3968. /**
  3969. * Updates the passed vector "result" from the starting index of the passed array.
  3970. */
  3971. Vector4.FromArrayToRef = function (array, offset, result) {
  3972. result.x = array[offset];
  3973. result.y = array[offset + 1];
  3974. result.z = array[offset + 2];
  3975. result.w = array[offset + 3];
  3976. };
  3977. /**
  3978. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3979. */
  3980. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3981. Vector4.FromArrayToRef(array, offset, result);
  3982. };
  3983. /**
  3984. * Updates the passed vector "result" coordinates from the passed floats.
  3985. */
  3986. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3987. result.x = x;
  3988. result.y = y;
  3989. result.z = z;
  3990. result.w = w;
  3991. };
  3992. /**
  3993. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3994. */
  3995. Vector4.Zero = function () {
  3996. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3997. };
  3998. /**
  3999. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4000. */
  4001. Vector4.One = function () {
  4002. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4003. };
  4004. /**
  4005. * Returns a new normalized Vector4 from the passed one.
  4006. */
  4007. Vector4.Normalize = function (vector) {
  4008. var result = Vector4.Zero();
  4009. Vector4.NormalizeToRef(vector, result);
  4010. return result;
  4011. };
  4012. /**
  4013. * Updates the passed vector "result" from the normalization of the passed one.
  4014. */
  4015. Vector4.NormalizeToRef = function (vector, result) {
  4016. result.copyFrom(vector);
  4017. result.normalize();
  4018. };
  4019. Vector4.Minimize = function (left, right) {
  4020. var min = left.clone();
  4021. min.minimizeInPlace(right);
  4022. return min;
  4023. };
  4024. Vector4.Maximize = function (left, right) {
  4025. var max = left.clone();
  4026. max.maximizeInPlace(right);
  4027. return max;
  4028. };
  4029. /**
  4030. * Returns the distance (float) between the vectors "value1" and "value2".
  4031. */
  4032. Vector4.Distance = function (value1, value2) {
  4033. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4034. };
  4035. /**
  4036. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4037. */
  4038. Vector4.DistanceSquared = function (value1, value2) {
  4039. var x = value1.x - value2.x;
  4040. var y = value1.y - value2.y;
  4041. var z = value1.z - value2.z;
  4042. var w = value1.w - value2.w;
  4043. return (x * x) + (y * y) + (z * z) + (w * w);
  4044. };
  4045. /**
  4046. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4047. */
  4048. Vector4.Center = function (value1, value2) {
  4049. var center = value1.add(value2);
  4050. center.scaleInPlace(0.5);
  4051. return center;
  4052. };
  4053. /**
  4054. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4055. * This methods computes transformed normalized direction vectors only.
  4056. */
  4057. Vector4.TransformNormal = function (vector, transformation) {
  4058. var result = Vector4.Zero();
  4059. Vector4.TransformNormalToRef(vector, transformation, result);
  4060. return result;
  4061. };
  4062. /**
  4063. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4064. * This methods computes transformed normalized direction vectors only.
  4065. */
  4066. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4067. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4068. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4069. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4070. result.x = x;
  4071. result.y = y;
  4072. result.z = z;
  4073. result.w = vector.w;
  4074. };
  4075. /**
  4076. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4077. * This methods computes transformed normalized direction vectors only.
  4078. */
  4079. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4080. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4081. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4082. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4083. result.w = w;
  4084. };
  4085. return Vector4;
  4086. }());
  4087. BABYLON.Vector4 = Vector4;
  4088. var Size = /** @class */ (function () {
  4089. /**
  4090. * Creates a Size object from the passed width and height (floats).
  4091. */
  4092. function Size(width, height) {
  4093. this.width = width;
  4094. this.height = height;
  4095. }
  4096. // Returns a string with the Size width and height.
  4097. Size.prototype.toString = function () {
  4098. return "{W: " + this.width + ", H: " + this.height + "}";
  4099. };
  4100. /**
  4101. * Returns the string "Size"
  4102. */
  4103. Size.prototype.getClassName = function () {
  4104. return "Size";
  4105. };
  4106. /**
  4107. * Returns the Size hash code.
  4108. */
  4109. Size.prototype.getHashCode = function () {
  4110. var hash = this.width || 0;
  4111. hash = (hash * 397) ^ (this.height || 0);
  4112. return hash;
  4113. };
  4114. /**
  4115. * Updates the current size from the passed one.
  4116. * Returns the updated Size.
  4117. */
  4118. Size.prototype.copyFrom = function (src) {
  4119. this.width = src.width;
  4120. this.height = src.height;
  4121. };
  4122. /**
  4123. * Updates in place the current Size from the passed floats.
  4124. * Returns the updated Size.
  4125. */
  4126. Size.prototype.copyFromFloats = function (width, height) {
  4127. this.width = width;
  4128. this.height = height;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates in place the current Size from the passed floats.
  4133. * Returns the updated Size.
  4134. */
  4135. Size.prototype.set = function (width, height) {
  4136. return this.copyFromFloats(width, height);
  4137. };
  4138. /**
  4139. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4140. */
  4141. Size.prototype.multiplyByFloats = function (w, h) {
  4142. return new Size(this.width * w, this.height * h);
  4143. };
  4144. /**
  4145. * Returns a new Size copied from the passed one.
  4146. */
  4147. Size.prototype.clone = function () {
  4148. return new Size(this.width, this.height);
  4149. };
  4150. /**
  4151. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4152. */
  4153. Size.prototype.equals = function (other) {
  4154. if (!other) {
  4155. return false;
  4156. }
  4157. return (this.width === other.width) && (this.height === other.height);
  4158. };
  4159. Object.defineProperty(Size.prototype, "surface", {
  4160. /**
  4161. * Returns the surface of the Size : width * height (float).
  4162. */
  4163. get: function () {
  4164. return this.width * this.height;
  4165. },
  4166. enumerable: true,
  4167. configurable: true
  4168. });
  4169. /**
  4170. * Returns a new Size set to (0.0, 0.0)
  4171. */
  4172. Size.Zero = function () {
  4173. return new Size(0.0, 0.0);
  4174. };
  4175. /**
  4176. * Returns a new Size set as the addition result of the current Size and the passed one.
  4177. */
  4178. Size.prototype.add = function (otherSize) {
  4179. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4180. return r;
  4181. };
  4182. /**
  4183. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4184. */
  4185. Size.prototype.subtract = function (otherSize) {
  4186. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4187. return r;
  4188. };
  4189. /**
  4190. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4191. */
  4192. Size.Lerp = function (start, end, amount) {
  4193. var w = start.width + ((end.width - start.width) * amount);
  4194. var h = start.height + ((end.height - start.height) * amount);
  4195. return new Size(w, h);
  4196. };
  4197. return Size;
  4198. }());
  4199. BABYLON.Size = Size;
  4200. var Quaternion = /** @class */ (function () {
  4201. /**
  4202. * Creates a new Quaternion from the passed floats.
  4203. */
  4204. function Quaternion(x, y, z, w) {
  4205. if (x === void 0) { x = 0.0; }
  4206. if (y === void 0) { y = 0.0; }
  4207. if (z === void 0) { z = 0.0; }
  4208. if (w === void 0) { w = 1.0; }
  4209. this.x = x;
  4210. this.y = y;
  4211. this.z = z;
  4212. this.w = w;
  4213. }
  4214. /**
  4215. * Returns a string with the Quaternion coordinates.
  4216. */
  4217. Quaternion.prototype.toString = function () {
  4218. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4219. };
  4220. /**
  4221. * Returns the string "Quaternion".
  4222. */
  4223. Quaternion.prototype.getClassName = function () {
  4224. return "Quaternion";
  4225. };
  4226. /**
  4227. * Returns the Quaternion hash code.
  4228. */
  4229. Quaternion.prototype.getHashCode = function () {
  4230. var hash = this.x || 0;
  4231. hash = (hash * 397) ^ (this.y || 0);
  4232. hash = (hash * 397) ^ (this.z || 0);
  4233. hash = (hash * 397) ^ (this.w || 0);
  4234. return hash;
  4235. };
  4236. /**
  4237. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4238. */
  4239. Quaternion.prototype.asArray = function () {
  4240. return [this.x, this.y, this.z, this.w];
  4241. };
  4242. /**
  4243. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4244. */
  4245. Quaternion.prototype.equals = function (otherQuaternion) {
  4246. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4247. };
  4248. /**
  4249. * Returns a new Quaternion copied from the current one.
  4250. */
  4251. Quaternion.prototype.clone = function () {
  4252. return new Quaternion(this.x, this.y, this.z, this.w);
  4253. };
  4254. /**
  4255. * Updates the current Quaternion from the passed one coordinates.
  4256. * Returns the updated Quaterion.
  4257. */
  4258. Quaternion.prototype.copyFrom = function (other) {
  4259. this.x = other.x;
  4260. this.y = other.y;
  4261. this.z = other.z;
  4262. this.w = other.w;
  4263. return this;
  4264. };
  4265. /**
  4266. * Updates the current Quaternion from the passed float coordinates.
  4267. * Returns the updated Quaterion.
  4268. */
  4269. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4270. this.x = x;
  4271. this.y = y;
  4272. this.z = z;
  4273. this.w = w;
  4274. return this;
  4275. };
  4276. /**
  4277. * Updates the current Quaternion from the passed float coordinates.
  4278. * Returns the updated Quaterion.
  4279. */
  4280. Quaternion.prototype.set = function (x, y, z, w) {
  4281. return this.copyFromFloats(x, y, z, w);
  4282. };
  4283. /**
  4284. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4285. */
  4286. Quaternion.prototype.add = function (other) {
  4287. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4288. };
  4289. /**
  4290. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4291. */
  4292. Quaternion.prototype.subtract = function (other) {
  4293. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4294. };
  4295. /**
  4296. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4297. */
  4298. Quaternion.prototype.scale = function (value) {
  4299. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4300. };
  4301. /**
  4302. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4303. */
  4304. Quaternion.prototype.multiply = function (q1) {
  4305. var result = new Quaternion(0, 0, 0, 1.0);
  4306. this.multiplyToRef(q1, result);
  4307. return result;
  4308. };
  4309. /**
  4310. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4311. * Returns the current Quaternion.
  4312. */
  4313. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4314. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4315. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4316. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4317. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4318. result.copyFromFloats(x, y, z, w);
  4319. return this;
  4320. };
  4321. /**
  4322. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4323. * Returns the updated Quaternion.
  4324. */
  4325. Quaternion.prototype.multiplyInPlace = function (q1) {
  4326. this.multiplyToRef(q1, this);
  4327. return this;
  4328. };
  4329. /**
  4330. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4331. * Returns the current Quaternion.
  4332. */
  4333. Quaternion.prototype.conjugateToRef = function (ref) {
  4334. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4335. return this;
  4336. };
  4337. /**
  4338. * Conjugates in place the current Quaternion.
  4339. * Returns the updated Quaternion.
  4340. */
  4341. Quaternion.prototype.conjugateInPlace = function () {
  4342. this.x *= -1;
  4343. this.y *= -1;
  4344. this.z *= -1;
  4345. return this;
  4346. };
  4347. /**
  4348. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4349. */
  4350. Quaternion.prototype.conjugate = function () {
  4351. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4352. return result;
  4353. };
  4354. /**
  4355. * Returns the Quaternion length (float).
  4356. */
  4357. Quaternion.prototype.length = function () {
  4358. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4359. };
  4360. /**
  4361. * Normalize in place the current Quaternion.
  4362. * Returns the updated Quaternion.
  4363. */
  4364. Quaternion.prototype.normalize = function () {
  4365. var length = 1.0 / this.length();
  4366. this.x *= length;
  4367. this.y *= length;
  4368. this.z *= length;
  4369. this.w *= length;
  4370. return this;
  4371. };
  4372. /**
  4373. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4374. */
  4375. Quaternion.prototype.toEulerAngles = function (order) {
  4376. if (order === void 0) { order = "YZX"; }
  4377. var result = Vector3.Zero();
  4378. this.toEulerAnglesToRef(result, order);
  4379. return result;
  4380. };
  4381. /**
  4382. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4383. * Returns the current Quaternion.
  4384. */
  4385. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4386. if (order === void 0) { order = "YZX"; }
  4387. var qz = this.z;
  4388. var qx = this.x;
  4389. var qy = this.y;
  4390. var qw = this.w;
  4391. var sqw = qw * qw;
  4392. var sqz = qz * qz;
  4393. var sqx = qx * qx;
  4394. var sqy = qy * qy;
  4395. var zAxisY = qy * qz - qx * qw;
  4396. var limit = .4999999;
  4397. if (zAxisY < -limit) {
  4398. result.y = 2 * Math.atan2(qy, qw);
  4399. result.x = Math.PI / 2;
  4400. result.z = 0;
  4401. }
  4402. else if (zAxisY > limit) {
  4403. result.y = 2 * Math.atan2(qy, qw);
  4404. result.x = -Math.PI / 2;
  4405. result.z = 0;
  4406. }
  4407. else {
  4408. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4409. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4410. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4411. }
  4412. return this;
  4413. };
  4414. /**
  4415. * Updates the passed rotation matrix with the current Quaternion values.
  4416. * Returns the current Quaternion.
  4417. */
  4418. Quaternion.prototype.toRotationMatrix = function (result) {
  4419. var xx = this.x * this.x;
  4420. var yy = this.y * this.y;
  4421. var zz = this.z * this.z;
  4422. var xy = this.x * this.y;
  4423. var zw = this.z * this.w;
  4424. var zx = this.z * this.x;
  4425. var yw = this.y * this.w;
  4426. var yz = this.y * this.z;
  4427. var xw = this.x * this.w;
  4428. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4429. result.m[1] = 2.0 * (xy + zw);
  4430. result.m[2] = 2.0 * (zx - yw);
  4431. result.m[3] = 0;
  4432. result.m[4] = 2.0 * (xy - zw);
  4433. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4434. result.m[6] = 2.0 * (yz + xw);
  4435. result.m[7] = 0;
  4436. result.m[8] = 2.0 * (zx + yw);
  4437. result.m[9] = 2.0 * (yz - xw);
  4438. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4439. result.m[11] = 0;
  4440. result.m[12] = 0;
  4441. result.m[13] = 0;
  4442. result.m[14] = 0;
  4443. result.m[15] = 1.0;
  4444. result._markAsUpdated();
  4445. return this;
  4446. };
  4447. /**
  4448. * Updates the current Quaternion from the passed rotation matrix values.
  4449. * Returns the updated Quaternion.
  4450. */
  4451. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4452. Quaternion.FromRotationMatrixToRef(matrix, this);
  4453. return this;
  4454. };
  4455. // Statics
  4456. /**
  4457. * Returns a new Quaternion set from the passed rotation matrix values.
  4458. */
  4459. Quaternion.FromRotationMatrix = function (matrix) {
  4460. var result = new Quaternion();
  4461. Quaternion.FromRotationMatrixToRef(matrix, result);
  4462. return result;
  4463. };
  4464. /**
  4465. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4466. */
  4467. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4468. var data = matrix.m;
  4469. var m11 = data[0], m12 = data[4], m13 = data[8];
  4470. var m21 = data[1], m22 = data[5], m23 = data[9];
  4471. var m31 = data[2], m32 = data[6], m33 = data[10];
  4472. var trace = m11 + m22 + m33;
  4473. var s;
  4474. if (trace > 0) {
  4475. s = 0.5 / Math.sqrt(trace + 1.0);
  4476. result.w = 0.25 / s;
  4477. result.x = (m32 - m23) * s;
  4478. result.y = (m13 - m31) * s;
  4479. result.z = (m21 - m12) * s;
  4480. }
  4481. else if (m11 > m22 && m11 > m33) {
  4482. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4483. result.w = (m32 - m23) / s;
  4484. result.x = 0.25 * s;
  4485. result.y = (m12 + m21) / s;
  4486. result.z = (m13 + m31) / s;
  4487. }
  4488. else if (m22 > m33) {
  4489. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4490. result.w = (m13 - m31) / s;
  4491. result.x = (m12 + m21) / s;
  4492. result.y = 0.25 * s;
  4493. result.z = (m23 + m32) / s;
  4494. }
  4495. else {
  4496. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4497. result.w = (m21 - m12) / s;
  4498. result.x = (m13 + m31) / s;
  4499. result.y = (m23 + m32) / s;
  4500. result.z = 0.25 * s;
  4501. }
  4502. };
  4503. /**
  4504. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4505. */
  4506. Quaternion.Zero = function () {
  4507. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4508. };
  4509. /**
  4510. * Returns a new Quaternion as the inverted current Quaternion.
  4511. */
  4512. Quaternion.Inverse = function (q) {
  4513. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4514. };
  4515. /**
  4516. * Returns the identity Quaternion.
  4517. */
  4518. Quaternion.Identity = function () {
  4519. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4520. };
  4521. Quaternion.IsIdentity = function (quaternion) {
  4522. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4523. };
  4524. /**
  4525. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4526. */
  4527. Quaternion.RotationAxis = function (axis, angle) {
  4528. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4529. };
  4530. /**
  4531. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4532. */
  4533. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4534. var sin = Math.sin(angle / 2);
  4535. axis.normalize();
  4536. result.w = Math.cos(angle / 2);
  4537. result.x = axis.x * sin;
  4538. result.y = axis.y * sin;
  4539. result.z = axis.z * sin;
  4540. return result;
  4541. };
  4542. /**
  4543. * Retuns a new Quaternion set from the starting index of the passed array.
  4544. */
  4545. Quaternion.FromArray = function (array, offset) {
  4546. if (!offset) {
  4547. offset = 0;
  4548. }
  4549. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4550. };
  4551. /**
  4552. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4553. */
  4554. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4555. var q = new Quaternion();
  4556. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4557. return q;
  4558. };
  4559. /**
  4560. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4561. */
  4562. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4563. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4564. var halfRoll = roll * 0.5;
  4565. var halfPitch = pitch * 0.5;
  4566. var halfYaw = yaw * 0.5;
  4567. var sinRoll = Math.sin(halfRoll);
  4568. var cosRoll = Math.cos(halfRoll);
  4569. var sinPitch = Math.sin(halfPitch);
  4570. var cosPitch = Math.cos(halfPitch);
  4571. var sinYaw = Math.sin(halfYaw);
  4572. var cosYaw = Math.cos(halfYaw);
  4573. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4574. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4575. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4576. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4577. };
  4578. /**
  4579. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4580. */
  4581. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4582. var result = new Quaternion();
  4583. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4584. return result;
  4585. };
  4586. /**
  4587. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4588. */
  4589. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4590. // Produces a quaternion from Euler angles in the z-x-z orientation
  4591. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4592. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4593. var halfBeta = beta * 0.5;
  4594. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4595. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4596. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4597. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4598. };
  4599. /**
  4600. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4601. * cf to Vector3.RotationFromAxis() documentation.
  4602. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4603. */
  4604. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4605. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4606. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4607. return quat;
  4608. };
  4609. /**
  4610. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4611. * cf to Vector3.RotationFromAxis() documentation.
  4612. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4613. */
  4614. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4615. var rotMat = MathTmp.Matrix[0];
  4616. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4617. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4618. };
  4619. Quaternion.Slerp = function (left, right, amount) {
  4620. var result = Quaternion.Identity();
  4621. Quaternion.SlerpToRef(left, right, amount, result);
  4622. return result;
  4623. };
  4624. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4625. var num2;
  4626. var num3;
  4627. var num = amount;
  4628. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4629. var flag = false;
  4630. if (num4 < 0) {
  4631. flag = true;
  4632. num4 = -num4;
  4633. }
  4634. if (num4 > 0.999999) {
  4635. num3 = 1 - num;
  4636. num2 = flag ? -num : num;
  4637. }
  4638. else {
  4639. var num5 = Math.acos(num4);
  4640. var num6 = (1.0 / Math.sin(num5));
  4641. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4642. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4643. }
  4644. result.x = (num3 * left.x) + (num2 * right.x);
  4645. result.y = (num3 * left.y) + (num2 * right.y);
  4646. result.z = (num3 * left.z) + (num2 * right.z);
  4647. result.w = (num3 * left.w) + (num2 * right.w);
  4648. };
  4649. /**
  4650. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4651. */
  4652. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4653. var squared = amount * amount;
  4654. var cubed = amount * squared;
  4655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4657. var part3 = (cubed - (2.0 * squared)) + amount;
  4658. var part4 = cubed - squared;
  4659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4661. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4662. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4663. return new Quaternion(x, y, z, w);
  4664. };
  4665. return Quaternion;
  4666. }());
  4667. BABYLON.Quaternion = Quaternion;
  4668. var Matrix = /** @class */ (function () {
  4669. function Matrix() {
  4670. this._isIdentity = false;
  4671. this._isIdentityDirty = true;
  4672. this.m = new Float32Array(16);
  4673. this._markAsUpdated();
  4674. }
  4675. Matrix.prototype._markAsUpdated = function () {
  4676. this.updateFlag = Matrix._updateFlagSeed++;
  4677. this._isIdentityDirty = true;
  4678. };
  4679. // Properties
  4680. /**
  4681. * Boolean : True is the matrix is the identity matrix
  4682. */
  4683. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4684. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4685. if (this._isIdentityDirty) {
  4686. this._isIdentityDirty = false;
  4687. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4688. this._isIdentity = false;
  4689. }
  4690. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4691. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4692. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4693. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4694. this._isIdentity = false;
  4695. }
  4696. else {
  4697. this._isIdentity = true;
  4698. }
  4699. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4700. this._isIdentity = false;
  4701. }
  4702. }
  4703. return this._isIdentity;
  4704. };
  4705. /**
  4706. * Returns the matrix determinant (float).
  4707. */
  4708. Matrix.prototype.determinant = function () {
  4709. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4710. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4711. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4712. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4713. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4714. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4715. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4716. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4717. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4718. };
  4719. // Methods
  4720. /**
  4721. * Returns the matrix underlying array.
  4722. */
  4723. Matrix.prototype.toArray = function () {
  4724. return this.m;
  4725. };
  4726. /**
  4727. * Returns the matrix underlying array.
  4728. */
  4729. Matrix.prototype.asArray = function () {
  4730. return this.toArray();
  4731. };
  4732. /**
  4733. * Inverts in place the Matrix.
  4734. * Returns the Matrix inverted.
  4735. */
  4736. Matrix.prototype.invert = function () {
  4737. this.invertToRef(this);
  4738. return this;
  4739. };
  4740. /**
  4741. * Sets all the matrix elements to zero.
  4742. * Returns the Matrix.
  4743. */
  4744. Matrix.prototype.reset = function () {
  4745. for (var index = 0; index < 16; index++) {
  4746. this.m[index] = 0.0;
  4747. }
  4748. this._markAsUpdated();
  4749. return this;
  4750. };
  4751. /**
  4752. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4753. */
  4754. Matrix.prototype.add = function (other) {
  4755. var result = new Matrix();
  4756. this.addToRef(other, result);
  4757. return result;
  4758. };
  4759. /**
  4760. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4761. * Returns the Matrix.
  4762. */
  4763. Matrix.prototype.addToRef = function (other, result) {
  4764. for (var index = 0; index < 16; index++) {
  4765. result.m[index] = this.m[index] + other.m[index];
  4766. }
  4767. result._markAsUpdated();
  4768. return this;
  4769. };
  4770. /**
  4771. * Adds in place the passed matrix to the current Matrix.
  4772. * Returns the updated Matrix.
  4773. */
  4774. Matrix.prototype.addToSelf = function (other) {
  4775. for (var index = 0; index < 16; index++) {
  4776. this.m[index] += other.m[index];
  4777. }
  4778. this._markAsUpdated();
  4779. return this;
  4780. };
  4781. /**
  4782. * Sets the passed matrix with the current inverted Matrix.
  4783. * Returns the unmodified current Matrix.
  4784. */
  4785. Matrix.prototype.invertToRef = function (other) {
  4786. var l1 = this.m[0];
  4787. var l2 = this.m[1];
  4788. var l3 = this.m[2];
  4789. var l4 = this.m[3];
  4790. var l5 = this.m[4];
  4791. var l6 = this.m[5];
  4792. var l7 = this.m[6];
  4793. var l8 = this.m[7];
  4794. var l9 = this.m[8];
  4795. var l10 = this.m[9];
  4796. var l11 = this.m[10];
  4797. var l12 = this.m[11];
  4798. var l13 = this.m[12];
  4799. var l14 = this.m[13];
  4800. var l15 = this.m[14];
  4801. var l16 = this.m[15];
  4802. var l17 = (l11 * l16) - (l12 * l15);
  4803. var l18 = (l10 * l16) - (l12 * l14);
  4804. var l19 = (l10 * l15) - (l11 * l14);
  4805. var l20 = (l9 * l16) - (l12 * l13);
  4806. var l21 = (l9 * l15) - (l11 * l13);
  4807. var l22 = (l9 * l14) - (l10 * l13);
  4808. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4809. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4810. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4811. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4812. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4813. var l28 = (l7 * l16) - (l8 * l15);
  4814. var l29 = (l6 * l16) - (l8 * l14);
  4815. var l30 = (l6 * l15) - (l7 * l14);
  4816. var l31 = (l5 * l16) - (l8 * l13);
  4817. var l32 = (l5 * l15) - (l7 * l13);
  4818. var l33 = (l5 * l14) - (l6 * l13);
  4819. var l34 = (l7 * l12) - (l8 * l11);
  4820. var l35 = (l6 * l12) - (l8 * l10);
  4821. var l36 = (l6 * l11) - (l7 * l10);
  4822. var l37 = (l5 * l12) - (l8 * l9);
  4823. var l38 = (l5 * l11) - (l7 * l9);
  4824. var l39 = (l5 * l10) - (l6 * l9);
  4825. other.m[0] = l23 * l27;
  4826. other.m[4] = l24 * l27;
  4827. other.m[8] = l25 * l27;
  4828. other.m[12] = l26 * l27;
  4829. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4830. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4831. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4832. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4833. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4834. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4835. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4836. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4837. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4838. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4839. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4840. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4841. other._markAsUpdated();
  4842. return this;
  4843. };
  4844. /**
  4845. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4846. * Returns the updated Matrix.
  4847. */
  4848. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4849. this.m[12] = x;
  4850. this.m[13] = y;
  4851. this.m[14] = z;
  4852. this._markAsUpdated();
  4853. return this;
  4854. };
  4855. /**
  4856. * Inserts the translation vector in the current Matrix.
  4857. * Returns the updated Matrix.
  4858. */
  4859. Matrix.prototype.setTranslation = function (vector3) {
  4860. this.m[12] = vector3.x;
  4861. this.m[13] = vector3.y;
  4862. this.m[14] = vector3.z;
  4863. this._markAsUpdated();
  4864. return this;
  4865. };
  4866. /**
  4867. * Returns a new Vector3 as the extracted translation from the Matrix.
  4868. */
  4869. Matrix.prototype.getTranslation = function () {
  4870. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4871. };
  4872. /**
  4873. * Fill a Vector3 with the extracted translation from the Matrix.
  4874. */
  4875. Matrix.prototype.getTranslationToRef = function (result) {
  4876. result.x = this.m[12];
  4877. result.y = this.m[13];
  4878. result.z = this.m[14];
  4879. return this;
  4880. };
  4881. /**
  4882. * Remove rotation and scaling part from the Matrix.
  4883. * Returns the updated Matrix.
  4884. */
  4885. Matrix.prototype.removeRotationAndScaling = function () {
  4886. this.setRowFromFloats(0, 1, 0, 0, 0);
  4887. this.setRowFromFloats(1, 0, 1, 0, 0);
  4888. this.setRowFromFloats(2, 0, 0, 1, 0);
  4889. return this;
  4890. };
  4891. /**
  4892. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4893. */
  4894. Matrix.prototype.multiply = function (other) {
  4895. var result = new Matrix();
  4896. this.multiplyToRef(other, result);
  4897. return result;
  4898. };
  4899. /**
  4900. * Updates the current Matrix from the passed one values.
  4901. * Returns the updated Matrix.
  4902. */
  4903. Matrix.prototype.copyFrom = function (other) {
  4904. for (var index = 0; index < 16; index++) {
  4905. this.m[index] = other.m[index];
  4906. }
  4907. this._markAsUpdated();
  4908. return this;
  4909. };
  4910. /**
  4911. * Populates the passed array from the starting index with the Matrix values.
  4912. * Returns the Matrix.
  4913. */
  4914. Matrix.prototype.copyToArray = function (array, offset) {
  4915. if (offset === void 0) { offset = 0; }
  4916. for (var index = 0; index < 16; index++) {
  4917. array[offset + index] = this.m[index];
  4918. }
  4919. return this;
  4920. };
  4921. /**
  4922. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4923. */
  4924. Matrix.prototype.multiplyToRef = function (other, result) {
  4925. this.multiplyToArray(other, result.m, 0);
  4926. result._markAsUpdated();
  4927. return this;
  4928. };
  4929. /**
  4930. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4931. */
  4932. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4933. var tm0 = this.m[0];
  4934. var tm1 = this.m[1];
  4935. var tm2 = this.m[2];
  4936. var tm3 = this.m[3];
  4937. var tm4 = this.m[4];
  4938. var tm5 = this.m[5];
  4939. var tm6 = this.m[6];
  4940. var tm7 = this.m[7];
  4941. var tm8 = this.m[8];
  4942. var tm9 = this.m[9];
  4943. var tm10 = this.m[10];
  4944. var tm11 = this.m[11];
  4945. var tm12 = this.m[12];
  4946. var tm13 = this.m[13];
  4947. var tm14 = this.m[14];
  4948. var tm15 = this.m[15];
  4949. var om0 = other.m[0];
  4950. var om1 = other.m[1];
  4951. var om2 = other.m[2];
  4952. var om3 = other.m[3];
  4953. var om4 = other.m[4];
  4954. var om5 = other.m[5];
  4955. var om6 = other.m[6];
  4956. var om7 = other.m[7];
  4957. var om8 = other.m[8];
  4958. var om9 = other.m[9];
  4959. var om10 = other.m[10];
  4960. var om11 = other.m[11];
  4961. var om12 = other.m[12];
  4962. var om13 = other.m[13];
  4963. var om14 = other.m[14];
  4964. var om15 = other.m[15];
  4965. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4966. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4967. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4968. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4969. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4970. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4971. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4972. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4973. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4974. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4975. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4976. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4977. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4978. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4979. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4980. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4981. return this;
  4982. };
  4983. /**
  4984. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4985. */
  4986. Matrix.prototype.equals = function (value) {
  4987. return value &&
  4988. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4989. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4990. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4991. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4992. };
  4993. /**
  4994. * Returns a new Matrix from the current Matrix.
  4995. */
  4996. Matrix.prototype.clone = function () {
  4997. 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]);
  4998. };
  4999. /**
  5000. * Returns the string "Matrix"
  5001. */
  5002. Matrix.prototype.getClassName = function () {
  5003. return "Matrix";
  5004. };
  5005. /**
  5006. * Returns the Matrix hash code.
  5007. */
  5008. Matrix.prototype.getHashCode = function () {
  5009. var hash = this.m[0] || 0;
  5010. for (var i = 1; i < 16; i++) {
  5011. hash = (hash * 397) ^ (this.m[i] || 0);
  5012. }
  5013. return hash;
  5014. };
  5015. /**
  5016. * Decomposes the current Matrix into :
  5017. * - a scale vector3 passed as a reference to update,
  5018. * - a rotation quaternion passed as a reference to update,
  5019. * - a translation vector3 passed as a reference to update.
  5020. * Returns the true if operation was successful.
  5021. */
  5022. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5023. translation.x = this.m[12];
  5024. translation.y = this.m[13];
  5025. translation.z = this.m[14];
  5026. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5027. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5028. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5029. if (this.determinant() <= 0) {
  5030. scale.y *= -1;
  5031. }
  5032. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5033. rotation.x = 0;
  5034. rotation.y = 0;
  5035. rotation.z = 0;
  5036. rotation.w = 1;
  5037. return false;
  5038. }
  5039. 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]);
  5040. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5041. return true;
  5042. };
  5043. /**
  5044. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5045. * @param ref matrix to store the result
  5046. */
  5047. Matrix.prototype.toNormalMatrix = function (ref) {
  5048. this.invertToRef(ref);
  5049. ref.transpose();
  5050. var m = ref.m;
  5051. 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);
  5052. };
  5053. /**
  5054. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5055. */
  5056. Matrix.prototype.getRotationMatrix = function () {
  5057. var result = Matrix.Identity();
  5058. this.getRotationMatrixToRef(result);
  5059. return result;
  5060. };
  5061. /**
  5062. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5063. * Returns the current Matrix.
  5064. */
  5065. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5066. var m = this.m;
  5067. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5068. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5069. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5070. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5071. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5072. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5073. 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);
  5074. return this;
  5075. };
  5076. // Statics
  5077. /**
  5078. * Returns a new Matrix set from the starting index of the passed array.
  5079. */
  5080. Matrix.FromArray = function (array, offset) {
  5081. var result = new Matrix();
  5082. if (!offset) {
  5083. offset = 0;
  5084. }
  5085. Matrix.FromArrayToRef(array, offset, result);
  5086. return result;
  5087. };
  5088. /**
  5089. * Sets the passed "result" matrix from the starting index of the passed array.
  5090. */
  5091. Matrix.FromArrayToRef = function (array, offset, result) {
  5092. for (var index = 0; index < 16; index++) {
  5093. result.m[index] = array[index + offset];
  5094. }
  5095. result._markAsUpdated();
  5096. };
  5097. /**
  5098. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5099. */
  5100. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5101. for (var index = 0; index < 16; index++) {
  5102. result.m[index] = array[index + offset] * scale;
  5103. }
  5104. result._markAsUpdated();
  5105. };
  5106. /**
  5107. * Sets the passed matrix "result" with the 16 passed floats.
  5108. */
  5109. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5110. result.m[0] = initialM11;
  5111. result.m[1] = initialM12;
  5112. result.m[2] = initialM13;
  5113. result.m[3] = initialM14;
  5114. result.m[4] = initialM21;
  5115. result.m[5] = initialM22;
  5116. result.m[6] = initialM23;
  5117. result.m[7] = initialM24;
  5118. result.m[8] = initialM31;
  5119. result.m[9] = initialM32;
  5120. result.m[10] = initialM33;
  5121. result.m[11] = initialM34;
  5122. result.m[12] = initialM41;
  5123. result.m[13] = initialM42;
  5124. result.m[14] = initialM43;
  5125. result.m[15] = initialM44;
  5126. result._markAsUpdated();
  5127. };
  5128. /**
  5129. * Returns the index-th row of the current matrix as a new Vector4.
  5130. */
  5131. Matrix.prototype.getRow = function (index) {
  5132. if (index < 0 || index > 3) {
  5133. return null;
  5134. }
  5135. var i = index * 4;
  5136. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5137. };
  5138. /**
  5139. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5140. * Returns the updated Matrix.
  5141. */
  5142. Matrix.prototype.setRow = function (index, row) {
  5143. if (index < 0 || index > 3) {
  5144. return this;
  5145. }
  5146. var i = index * 4;
  5147. this.m[i + 0] = row.x;
  5148. this.m[i + 1] = row.y;
  5149. this.m[i + 2] = row.z;
  5150. this.m[i + 3] = row.w;
  5151. this._markAsUpdated();
  5152. return this;
  5153. };
  5154. /**
  5155. * Compute the transpose of the matrix.
  5156. * Returns a new Matrix.
  5157. */
  5158. Matrix.prototype.transpose = function () {
  5159. return Matrix.Transpose(this);
  5160. };
  5161. /**
  5162. * Compute the transpose of the matrix.
  5163. * Returns the current matrix.
  5164. */
  5165. Matrix.prototype.transposeToRef = function (result) {
  5166. Matrix.TransposeToRef(this, result);
  5167. return this;
  5168. };
  5169. /**
  5170. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5171. * Returns the updated Matrix.
  5172. */
  5173. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5174. if (index < 0 || index > 3) {
  5175. return this;
  5176. }
  5177. var i = index * 4;
  5178. this.m[i + 0] = x;
  5179. this.m[i + 1] = y;
  5180. this.m[i + 2] = z;
  5181. this.m[i + 3] = w;
  5182. this._markAsUpdated();
  5183. return this;
  5184. };
  5185. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5186. /**
  5187. * Static identity matrix to be used as readonly matrix
  5188. * Must not be updated.
  5189. */
  5190. get: function () {
  5191. return Matrix._identityReadOnly;
  5192. },
  5193. enumerable: true,
  5194. configurable: true
  5195. });
  5196. /**
  5197. * Returns a new Matrix set from the 16 passed floats.
  5198. */
  5199. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5200. var result = new Matrix();
  5201. result.m[0] = initialM11;
  5202. result.m[1] = initialM12;
  5203. result.m[2] = initialM13;
  5204. result.m[3] = initialM14;
  5205. result.m[4] = initialM21;
  5206. result.m[5] = initialM22;
  5207. result.m[6] = initialM23;
  5208. result.m[7] = initialM24;
  5209. result.m[8] = initialM31;
  5210. result.m[9] = initialM32;
  5211. result.m[10] = initialM33;
  5212. result.m[11] = initialM34;
  5213. result.m[12] = initialM41;
  5214. result.m[13] = initialM42;
  5215. result.m[14] = initialM43;
  5216. result.m[15] = initialM44;
  5217. return result;
  5218. };
  5219. /**
  5220. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5221. */
  5222. Matrix.Compose = function (scale, rotation, translation) {
  5223. var result = Matrix.Identity();
  5224. Matrix.ComposeToRef(scale, rotation, translation, result);
  5225. return result;
  5226. };
  5227. /**
  5228. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5229. */
  5230. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5231. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5232. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5233. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5234. result.setTranslation(translation);
  5235. };
  5236. /**
  5237. * Returns a new indentity Matrix.
  5238. */
  5239. Matrix.Identity = function () {
  5240. 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);
  5241. };
  5242. /**
  5243. * Sets the passed "result" as an identity matrix.
  5244. */
  5245. Matrix.IdentityToRef = function (result) {
  5246. 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);
  5247. };
  5248. /**
  5249. * Returns a new zero Matrix.
  5250. */
  5251. Matrix.Zero = function () {
  5252. 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);
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the X axis.
  5256. */
  5257. Matrix.RotationX = function (angle) {
  5258. var result = new Matrix();
  5259. Matrix.RotationXToRef(angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Returns a new Matrix as the passed inverted one.
  5264. */
  5265. Matrix.Invert = function (source) {
  5266. var result = new Matrix();
  5267. source.invertToRef(result);
  5268. return result;
  5269. };
  5270. /**
  5271. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5272. */
  5273. Matrix.RotationXToRef = function (angle, result) {
  5274. var s = Math.sin(angle);
  5275. var c = Math.cos(angle);
  5276. result.m[0] = 1.0;
  5277. result.m[15] = 1.0;
  5278. result.m[5] = c;
  5279. result.m[10] = c;
  5280. result.m[9] = -s;
  5281. result.m[6] = s;
  5282. result.m[1] = 0.0;
  5283. result.m[2] = 0.0;
  5284. result.m[3] = 0.0;
  5285. result.m[4] = 0.0;
  5286. result.m[7] = 0.0;
  5287. result.m[8] = 0.0;
  5288. result.m[11] = 0.0;
  5289. result.m[12] = 0.0;
  5290. result.m[13] = 0.0;
  5291. result.m[14] = 0.0;
  5292. result._markAsUpdated();
  5293. };
  5294. /**
  5295. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5296. */
  5297. Matrix.RotationY = function (angle) {
  5298. var result = new Matrix();
  5299. Matrix.RotationYToRef(angle, result);
  5300. return result;
  5301. };
  5302. /**
  5303. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5304. */
  5305. Matrix.RotationYToRef = function (angle, result) {
  5306. var s = Math.sin(angle);
  5307. var c = Math.cos(angle);
  5308. result.m[5] = 1.0;
  5309. result.m[15] = 1.0;
  5310. result.m[0] = c;
  5311. result.m[2] = -s;
  5312. result.m[8] = s;
  5313. result.m[10] = c;
  5314. result.m[1] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[6] = 0.0;
  5318. result.m[7] = 0.0;
  5319. result.m[9] = 0.0;
  5320. result.m[11] = 0.0;
  5321. result.m[12] = 0.0;
  5322. result.m[13] = 0.0;
  5323. result.m[14] = 0.0;
  5324. result._markAsUpdated();
  5325. };
  5326. /**
  5327. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5328. */
  5329. Matrix.RotationZ = function (angle) {
  5330. var result = new Matrix();
  5331. Matrix.RotationZToRef(angle, result);
  5332. return result;
  5333. };
  5334. /**
  5335. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5336. */
  5337. Matrix.RotationZToRef = function (angle, result) {
  5338. var s = Math.sin(angle);
  5339. var c = Math.cos(angle);
  5340. result.m[10] = 1.0;
  5341. result.m[15] = 1.0;
  5342. result.m[0] = c;
  5343. result.m[1] = s;
  5344. result.m[4] = -s;
  5345. result.m[5] = c;
  5346. result.m[2] = 0.0;
  5347. result.m[3] = 0.0;
  5348. result.m[6] = 0.0;
  5349. result.m[7] = 0.0;
  5350. result.m[8] = 0.0;
  5351. result.m[9] = 0.0;
  5352. result.m[11] = 0.0;
  5353. result.m[12] = 0.0;
  5354. result.m[13] = 0.0;
  5355. result.m[14] = 0.0;
  5356. result._markAsUpdated();
  5357. };
  5358. /**
  5359. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5360. */
  5361. Matrix.RotationAxis = function (axis, angle) {
  5362. var result = Matrix.Zero();
  5363. Matrix.RotationAxisToRef(axis, angle, result);
  5364. return result;
  5365. };
  5366. /**
  5367. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5368. */
  5369. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5370. var s = Math.sin(-angle);
  5371. var c = Math.cos(-angle);
  5372. var c1 = 1 - c;
  5373. axis.normalize();
  5374. result.m[0] = (axis.x * axis.x) * c1 + c;
  5375. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5376. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5377. result.m[3] = 0.0;
  5378. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5379. result.m[5] = (axis.y * axis.y) * c1 + c;
  5380. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5381. result.m[7] = 0.0;
  5382. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5383. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5384. result.m[10] = (axis.z * axis.z) * c1 + c;
  5385. result.m[11] = 0.0;
  5386. result.m[15] = 1.0;
  5387. result._markAsUpdated();
  5388. };
  5389. /**
  5390. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5391. */
  5392. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5393. var result = new Matrix();
  5394. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5395. return result;
  5396. };
  5397. /**
  5398. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5399. */
  5400. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5401. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5402. this._tempQuaternion.toRotationMatrix(result);
  5403. };
  5404. /**
  5405. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5406. */
  5407. Matrix.Scaling = function (x, y, z) {
  5408. var result = Matrix.Zero();
  5409. Matrix.ScalingToRef(x, y, z, result);
  5410. return result;
  5411. };
  5412. /**
  5413. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5414. */
  5415. Matrix.ScalingToRef = function (x, y, z, result) {
  5416. result.m[0] = x;
  5417. result.m[1] = 0.0;
  5418. result.m[2] = 0.0;
  5419. result.m[3] = 0.0;
  5420. result.m[4] = 0.0;
  5421. result.m[5] = y;
  5422. result.m[6] = 0.0;
  5423. result.m[7] = 0.0;
  5424. result.m[8] = 0.0;
  5425. result.m[9] = 0.0;
  5426. result.m[10] = z;
  5427. result.m[11] = 0.0;
  5428. result.m[12] = 0.0;
  5429. result.m[13] = 0.0;
  5430. result.m[14] = 0.0;
  5431. result.m[15] = 1.0;
  5432. result._markAsUpdated();
  5433. };
  5434. /**
  5435. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5436. */
  5437. Matrix.Translation = function (x, y, z) {
  5438. var result = Matrix.Identity();
  5439. Matrix.TranslationToRef(x, y, z, result);
  5440. return result;
  5441. };
  5442. /**
  5443. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5444. */
  5445. Matrix.TranslationToRef = function (x, y, z, result) {
  5446. 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);
  5447. };
  5448. /**
  5449. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5450. * @param startValue defines the start value
  5451. * @param endValue defines the end value
  5452. * @param gradient defines the gradient factor
  5453. * @returns the new matrix
  5454. */
  5455. Matrix.Lerp = function (startValue, endValue, gradient) {
  5456. var result = Matrix.Zero();
  5457. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5458. return result;
  5459. };
  5460. /**
  5461. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5462. * @param startValue defines the start value
  5463. * @param endValue defines the end value
  5464. * @param gradient defines the gradient factor
  5465. * @param result defines the Matrix object where to store data
  5466. */
  5467. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5468. for (var index = 0; index < 16; index++) {
  5469. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5470. }
  5471. result._markAsUpdated();
  5472. };
  5473. /**
  5474. * Returns a new Matrix whose values are computed by :
  5475. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5476. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5477. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5478. */
  5479. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5480. var startScale = new Vector3(0, 0, 0);
  5481. var startRotation = new Quaternion();
  5482. var startTranslation = new Vector3(0, 0, 0);
  5483. startValue.decompose(startScale, startRotation, startTranslation);
  5484. var endScale = new Vector3(0, 0, 0);
  5485. var endRotation = new Quaternion();
  5486. var endTranslation = new Vector3(0, 0, 0);
  5487. endValue.decompose(endScale, endRotation, endTranslation);
  5488. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5489. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5490. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5491. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5492. };
  5493. /**
  5494. * 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".
  5495. * This methods works for a Left-Handed system.
  5496. */
  5497. Matrix.LookAtLH = function (eye, target, up) {
  5498. var result = Matrix.Zero();
  5499. Matrix.LookAtLHToRef(eye, target, up, result);
  5500. return result;
  5501. };
  5502. /**
  5503. * 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".
  5504. * This methods works for a Left-Handed system.
  5505. */
  5506. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5507. // Z axis
  5508. target.subtractToRef(eye, this._zAxis);
  5509. this._zAxis.normalize();
  5510. // X axis
  5511. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5512. if (this._xAxis.lengthSquared() === 0) {
  5513. this._xAxis.x = 1.0;
  5514. }
  5515. else {
  5516. this._xAxis.normalize();
  5517. }
  5518. // Y axis
  5519. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5520. this._yAxis.normalize();
  5521. // Eye angles
  5522. var ex = -Vector3.Dot(this._xAxis, eye);
  5523. var ey = -Vector3.Dot(this._yAxis, eye);
  5524. var ez = -Vector3.Dot(this._zAxis, eye);
  5525. 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);
  5526. };
  5527. /**
  5528. * 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".
  5529. * This methods works for a Right-Handed system.
  5530. */
  5531. Matrix.LookAtRH = function (eye, target, up) {
  5532. var result = Matrix.Zero();
  5533. Matrix.LookAtRHToRef(eye, target, up, result);
  5534. return result;
  5535. };
  5536. /**
  5537. * 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".
  5538. * This methods works for a Left-Handed system.
  5539. */
  5540. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5541. // Z axis
  5542. eye.subtractToRef(target, this._zAxis);
  5543. this._zAxis.normalize();
  5544. // X axis
  5545. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5546. if (this._xAxis.lengthSquared() === 0) {
  5547. this._xAxis.x = 1.0;
  5548. }
  5549. else {
  5550. this._xAxis.normalize();
  5551. }
  5552. // Y axis
  5553. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5554. this._yAxis.normalize();
  5555. // Eye angles
  5556. var ex = -Vector3.Dot(this._xAxis, eye);
  5557. var ey = -Vector3.Dot(this._yAxis, eye);
  5558. var ez = -Vector3.Dot(this._zAxis, eye);
  5559. 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);
  5560. };
  5561. /**
  5562. * 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.
  5563. */
  5564. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5565. var matrix = Matrix.Zero();
  5566. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5567. return matrix;
  5568. };
  5569. /**
  5570. * 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.
  5571. */
  5572. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5573. var n = znear;
  5574. var f = zfar;
  5575. var a = 2.0 / width;
  5576. var b = 2.0 / height;
  5577. var c = 2.0 / (f - n);
  5578. var d = -(f + n) / (f - n);
  5579. 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);
  5580. };
  5581. /**
  5582. * 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.
  5583. */
  5584. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5585. var matrix = Matrix.Zero();
  5586. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5587. return matrix;
  5588. };
  5589. /**
  5590. * 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.
  5591. */
  5592. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5593. var n = znear;
  5594. var f = zfar;
  5595. var a = 2.0 / (right - left);
  5596. var b = 2.0 / (top - bottom);
  5597. var c = 2.0 / (f - n);
  5598. var d = -(f + n) / (f - n);
  5599. var i0 = (left + right) / (left - right);
  5600. var i1 = (top + bottom) / (bottom - top);
  5601. 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);
  5602. };
  5603. /**
  5604. * 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.
  5605. */
  5606. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5607. var matrix = Matrix.Zero();
  5608. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5609. return matrix;
  5610. };
  5611. /**
  5612. * 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.
  5613. */
  5614. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5615. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5616. result.m[10] *= -1.0;
  5617. };
  5618. /**
  5619. * 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.
  5620. */
  5621. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5622. var matrix = Matrix.Zero();
  5623. var n = znear;
  5624. var f = zfar;
  5625. var a = 2.0 * n / width;
  5626. var b = 2.0 * n / height;
  5627. var c = (f + n) / (f - n);
  5628. var d = -2.0 * f * n / (f - n);
  5629. 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);
  5630. return matrix;
  5631. };
  5632. /**
  5633. * 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.
  5634. */
  5635. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5636. var matrix = Matrix.Zero();
  5637. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5638. return matrix;
  5639. };
  5640. /**
  5641. * 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.
  5642. */
  5643. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5645. var n = znear;
  5646. var f = zfar;
  5647. var t = 1.0 / (Math.tan(fov * 0.5));
  5648. var a = isVerticalFovFixed ? (t / aspect) : t;
  5649. var b = isVerticalFovFixed ? t : (t * aspect);
  5650. var c = (f + n) / (f - n);
  5651. var d = -2.0 * f * n / (f - n);
  5652. 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);
  5653. };
  5654. /**
  5655. * 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.
  5656. */
  5657. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * 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.
  5664. */
  5665. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5666. //alternatively this could be expressed as:
  5667. // m = PerspectiveFovLHToRef
  5668. // m[10] *= -1.0;
  5669. // m[11] *= -1.0;
  5670. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5671. var n = znear;
  5672. var f = zfar;
  5673. var t = 1.0 / (Math.tan(fov * 0.5));
  5674. var a = isVerticalFovFixed ? (t / aspect) : t;
  5675. var b = isVerticalFovFixed ? t : (t * aspect);
  5676. var c = -(f + n) / (f - n);
  5677. var d = -2 * f * n / (f - n);
  5678. 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);
  5679. };
  5680. /**
  5681. * 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.
  5682. */
  5683. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5684. if (rightHanded === void 0) { rightHanded = false; }
  5685. var rightHandedFactor = rightHanded ? -1 : 1;
  5686. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5687. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5688. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5689. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5690. var xScale = 2.0 / (leftTan + rightTan);
  5691. var yScale = 2.0 / (upTan + downTan);
  5692. result.m[0] = xScale;
  5693. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5694. result.m[5] = yScale;
  5695. result.m[6] = result.m[7] = 0.0;
  5696. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5697. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5698. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5699. result.m[10] = -zfar / (znear - zfar);
  5700. result.m[11] = 1.0 * rightHandedFactor;
  5701. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5702. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5703. // result.m[14] = (znear * zfar) / (znear - zfar);
  5704. result._markAsUpdated();
  5705. };
  5706. /**
  5707. * Returns the final transformation matrix : world * view * projection * viewport
  5708. */
  5709. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5710. var cw = viewport.width;
  5711. var ch = viewport.height;
  5712. var cx = viewport.x;
  5713. var cy = viewport.y;
  5714. 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);
  5715. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5716. };
  5717. /**
  5718. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5719. */
  5720. Matrix.GetAsMatrix2x2 = function (matrix) {
  5721. return new Float32Array([
  5722. matrix.m[0], matrix.m[1],
  5723. matrix.m[4], matrix.m[5]
  5724. ]);
  5725. };
  5726. /**
  5727. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5728. */
  5729. Matrix.GetAsMatrix3x3 = function (matrix) {
  5730. return new Float32Array([
  5731. matrix.m[0], matrix.m[1], matrix.m[2],
  5732. matrix.m[4], matrix.m[5], matrix.m[6],
  5733. matrix.m[8], matrix.m[9], matrix.m[10]
  5734. ]);
  5735. };
  5736. /**
  5737. * Compute the transpose of the passed Matrix.
  5738. * Returns a new Matrix.
  5739. */
  5740. Matrix.Transpose = function (matrix) {
  5741. var result = new Matrix();
  5742. Matrix.TransposeToRef(matrix, result);
  5743. return result;
  5744. };
  5745. /**
  5746. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5747. */
  5748. Matrix.TransposeToRef = function (matrix, result) {
  5749. result.m[0] = matrix.m[0];
  5750. result.m[1] = matrix.m[4];
  5751. result.m[2] = matrix.m[8];
  5752. result.m[3] = matrix.m[12];
  5753. result.m[4] = matrix.m[1];
  5754. result.m[5] = matrix.m[5];
  5755. result.m[6] = matrix.m[9];
  5756. result.m[7] = matrix.m[13];
  5757. result.m[8] = matrix.m[2];
  5758. result.m[9] = matrix.m[6];
  5759. result.m[10] = matrix.m[10];
  5760. result.m[11] = matrix.m[14];
  5761. result.m[12] = matrix.m[3];
  5762. result.m[13] = matrix.m[7];
  5763. result.m[14] = matrix.m[11];
  5764. result.m[15] = matrix.m[15];
  5765. };
  5766. /**
  5767. * Returns a new Matrix as the reflection matrix across the passed plane.
  5768. */
  5769. Matrix.Reflection = function (plane) {
  5770. var matrix = new Matrix();
  5771. Matrix.ReflectionToRef(plane, matrix);
  5772. return matrix;
  5773. };
  5774. /**
  5775. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5776. */
  5777. Matrix.ReflectionToRef = function (plane, result) {
  5778. plane.normalize();
  5779. var x = plane.normal.x;
  5780. var y = plane.normal.y;
  5781. var z = plane.normal.z;
  5782. var temp = -2 * x;
  5783. var temp2 = -2 * y;
  5784. var temp3 = -2 * z;
  5785. result.m[0] = (temp * x) + 1;
  5786. result.m[1] = temp2 * x;
  5787. result.m[2] = temp3 * x;
  5788. result.m[3] = 0.0;
  5789. result.m[4] = temp * y;
  5790. result.m[5] = (temp2 * y) + 1;
  5791. result.m[6] = temp3 * y;
  5792. result.m[7] = 0.0;
  5793. result.m[8] = temp * z;
  5794. result.m[9] = temp2 * z;
  5795. result.m[10] = (temp3 * z) + 1;
  5796. result.m[11] = 0.0;
  5797. result.m[12] = temp * plane.d;
  5798. result.m[13] = temp2 * plane.d;
  5799. result.m[14] = temp3 * plane.d;
  5800. result.m[15] = 1.0;
  5801. result._markAsUpdated();
  5802. };
  5803. /**
  5804. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5805. */
  5806. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5807. result.m[0] = xaxis.x;
  5808. result.m[1] = xaxis.y;
  5809. result.m[2] = xaxis.z;
  5810. result.m[3] = 0.0;
  5811. result.m[4] = yaxis.x;
  5812. result.m[5] = yaxis.y;
  5813. result.m[6] = yaxis.z;
  5814. result.m[7] = 0.0;
  5815. result.m[8] = zaxis.x;
  5816. result.m[9] = zaxis.y;
  5817. result.m[10] = zaxis.z;
  5818. result.m[11] = 0.0;
  5819. result.m[12] = 0.0;
  5820. result.m[13] = 0.0;
  5821. result.m[14] = 0.0;
  5822. result.m[15] = 1.0;
  5823. result._markAsUpdated();
  5824. };
  5825. /**
  5826. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5827. */
  5828. Matrix.FromQuaternionToRef = function (quat, result) {
  5829. var xx = quat.x * quat.x;
  5830. var yy = quat.y * quat.y;
  5831. var zz = quat.z * quat.z;
  5832. var xy = quat.x * quat.y;
  5833. var zw = quat.z * quat.w;
  5834. var zx = quat.z * quat.x;
  5835. var yw = quat.y * quat.w;
  5836. var yz = quat.y * quat.z;
  5837. var xw = quat.x * quat.w;
  5838. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5839. result.m[1] = 2.0 * (xy + zw);
  5840. result.m[2] = 2.0 * (zx - yw);
  5841. result.m[3] = 0.0;
  5842. result.m[4] = 2.0 * (xy - zw);
  5843. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5844. result.m[6] = 2.0 * (yz + xw);
  5845. result.m[7] = 0.0;
  5846. result.m[8] = 2.0 * (zx + yw);
  5847. result.m[9] = 2.0 * (yz - xw);
  5848. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5849. result.m[11] = 0.0;
  5850. result.m[12] = 0.0;
  5851. result.m[13] = 0.0;
  5852. result.m[14] = 0.0;
  5853. result.m[15] = 1.0;
  5854. result._markAsUpdated();
  5855. };
  5856. Matrix._tempQuaternion = new Quaternion();
  5857. Matrix._xAxis = Vector3.Zero();
  5858. Matrix._yAxis = Vector3.Zero();
  5859. Matrix._zAxis = Vector3.Zero();
  5860. Matrix._updateFlagSeed = 0;
  5861. Matrix._identityReadOnly = Matrix.Identity();
  5862. return Matrix;
  5863. }());
  5864. BABYLON.Matrix = Matrix;
  5865. var Plane = /** @class */ (function () {
  5866. /**
  5867. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5868. */
  5869. function Plane(a, b, c, d) {
  5870. this.normal = new Vector3(a, b, c);
  5871. this.d = d;
  5872. }
  5873. /**
  5874. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5875. */
  5876. Plane.prototype.asArray = function () {
  5877. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5878. };
  5879. // Methods
  5880. /**
  5881. * Returns a new plane copied from the current Plane.
  5882. */
  5883. Plane.prototype.clone = function () {
  5884. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5885. };
  5886. /**
  5887. * Returns the string "Plane".
  5888. */
  5889. Plane.prototype.getClassName = function () {
  5890. return "Plane";
  5891. };
  5892. /**
  5893. * Returns the Plane hash code.
  5894. */
  5895. Plane.prototype.getHashCode = function () {
  5896. var hash = this.normal.getHashCode();
  5897. hash = (hash * 397) ^ (this.d || 0);
  5898. return hash;
  5899. };
  5900. /**
  5901. * Normalize the current Plane in place.
  5902. * Returns the updated Plane.
  5903. */
  5904. Plane.prototype.normalize = function () {
  5905. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5906. var magnitude = 0.0;
  5907. if (norm !== 0) {
  5908. magnitude = 1.0 / norm;
  5909. }
  5910. this.normal.x *= magnitude;
  5911. this.normal.y *= magnitude;
  5912. this.normal.z *= magnitude;
  5913. this.d *= magnitude;
  5914. return this;
  5915. };
  5916. /**
  5917. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5918. */
  5919. Plane.prototype.transform = function (transformation) {
  5920. var transposedMatrix = Matrix.Transpose(transformation);
  5921. var x = this.normal.x;
  5922. var y = this.normal.y;
  5923. var z = this.normal.z;
  5924. var d = this.d;
  5925. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5926. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5927. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5928. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5929. return new Plane(normalX, normalY, normalZ, finalD);
  5930. };
  5931. /**
  5932. * Returns the dot product (float) of the point coordinates and the plane normal.
  5933. */
  5934. Plane.prototype.dotCoordinate = function (point) {
  5935. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5936. };
  5937. /**
  5938. * Updates the current Plane from the plane defined by the three passed points.
  5939. * Returns the updated Plane.
  5940. */
  5941. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5942. var x1 = point2.x - point1.x;
  5943. var y1 = point2.y - point1.y;
  5944. var z1 = point2.z - point1.z;
  5945. var x2 = point3.x - point1.x;
  5946. var y2 = point3.y - point1.y;
  5947. var z2 = point3.z - point1.z;
  5948. var yz = (y1 * z2) - (z1 * y2);
  5949. var xz = (z1 * x2) - (x1 * z2);
  5950. var xy = (x1 * y2) - (y1 * x2);
  5951. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5952. var invPyth;
  5953. if (pyth !== 0) {
  5954. invPyth = 1.0 / pyth;
  5955. }
  5956. else {
  5957. invPyth = 0.0;
  5958. }
  5959. this.normal.x = yz * invPyth;
  5960. this.normal.y = xz * invPyth;
  5961. this.normal.z = xy * invPyth;
  5962. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5963. return this;
  5964. };
  5965. /**
  5966. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5967. */
  5968. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5969. var dot = Vector3.Dot(this.normal, direction);
  5970. return (dot <= epsilon);
  5971. };
  5972. /**
  5973. * Returns the signed distance (float) from the passed point to the Plane.
  5974. */
  5975. Plane.prototype.signedDistanceTo = function (point) {
  5976. return Vector3.Dot(point, this.normal) + this.d;
  5977. };
  5978. // Statics
  5979. /**
  5980. * Returns a new Plane from the passed array.
  5981. */
  5982. Plane.FromArray = function (array) {
  5983. return new Plane(array[0], array[1], array[2], array[3]);
  5984. };
  5985. /**
  5986. * Returns a new Plane defined by the three passed points.
  5987. */
  5988. Plane.FromPoints = function (point1, point2, point3) {
  5989. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5990. result.copyFromPoints(point1, point2, point3);
  5991. return result;
  5992. };
  5993. /**
  5994. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5995. * Note : the vector "normal" is updated because normalized.
  5996. */
  5997. Plane.FromPositionAndNormal = function (origin, normal) {
  5998. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5999. normal.normalize();
  6000. result.normal = normal;
  6001. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6002. return result;
  6003. };
  6004. /**
  6005. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6006. */
  6007. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6008. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6009. return Vector3.Dot(point, normal) + d;
  6010. };
  6011. return Plane;
  6012. }());
  6013. BABYLON.Plane = Plane;
  6014. var Viewport = /** @class */ (function () {
  6015. /**
  6016. * Creates a Viewport object located at (x, y) and sized (width, height).
  6017. */
  6018. function Viewport(x, y, width, height) {
  6019. this.x = x;
  6020. this.y = y;
  6021. this.width = width;
  6022. this.height = height;
  6023. }
  6024. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6025. if (renderWidthOrEngine.getRenderWidth) {
  6026. var engine = renderWidthOrEngine;
  6027. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6028. }
  6029. var renderWidth = renderWidthOrEngine;
  6030. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6031. };
  6032. /**
  6033. * Returns a new Viewport copied from the current one.
  6034. */
  6035. Viewport.prototype.clone = function () {
  6036. return new Viewport(this.x, this.y, this.width, this.height);
  6037. };
  6038. return Viewport;
  6039. }());
  6040. BABYLON.Viewport = Viewport;
  6041. var Frustum = /** @class */ (function () {
  6042. function Frustum() {
  6043. }
  6044. /**
  6045. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6046. */
  6047. Frustum.GetPlanes = function (transform) {
  6048. var frustumPlanes = [];
  6049. for (var index = 0; index < 6; index++) {
  6050. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6051. }
  6052. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6053. return frustumPlanes;
  6054. };
  6055. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6056. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6057. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6058. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6059. frustumPlane.d = transform.m[15] + transform.m[14];
  6060. frustumPlane.normalize();
  6061. };
  6062. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6063. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6064. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6065. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6066. frustumPlane.d = transform.m[15] - transform.m[14];
  6067. frustumPlane.normalize();
  6068. };
  6069. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6070. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6071. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6072. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6073. frustumPlane.d = transform.m[15] + transform.m[12];
  6074. frustumPlane.normalize();
  6075. };
  6076. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6077. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6078. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6079. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6080. frustumPlane.d = transform.m[15] - transform.m[12];
  6081. frustumPlane.normalize();
  6082. };
  6083. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6084. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6085. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6086. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6087. frustumPlane.d = transform.m[15] - transform.m[13];
  6088. frustumPlane.normalize();
  6089. };
  6090. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6091. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6092. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6093. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6094. frustumPlane.d = transform.m[15] + transform.m[13];
  6095. frustumPlane.normalize();
  6096. };
  6097. /**
  6098. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6099. */
  6100. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6101. // Near
  6102. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6103. // Far
  6104. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6105. // Left
  6106. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6107. // Right
  6108. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6109. // Top
  6110. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6111. // Bottom
  6112. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6113. };
  6114. return Frustum;
  6115. }());
  6116. BABYLON.Frustum = Frustum;
  6117. var Space;
  6118. (function (Space) {
  6119. Space[Space["LOCAL"] = 0] = "LOCAL";
  6120. Space[Space["WORLD"] = 1] = "WORLD";
  6121. Space[Space["BONE"] = 2] = "BONE";
  6122. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6123. var Axis = /** @class */ (function () {
  6124. function Axis() {
  6125. }
  6126. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6127. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6128. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6129. return Axis;
  6130. }());
  6131. BABYLON.Axis = Axis;
  6132. ;
  6133. var BezierCurve = /** @class */ (function () {
  6134. function BezierCurve() {
  6135. }
  6136. /**
  6137. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6138. */
  6139. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6140. // Extract X (which is equal to time here)
  6141. var f0 = 1 - 3 * x2 + 3 * x1;
  6142. var f1 = 3 * x2 - 6 * x1;
  6143. var f2 = 3 * x1;
  6144. var refinedT = t;
  6145. for (var i = 0; i < 5; i++) {
  6146. var refinedT2 = refinedT * refinedT;
  6147. var refinedT3 = refinedT2 * refinedT;
  6148. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6149. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6150. refinedT -= (x - t) * slope;
  6151. refinedT = Math.min(1, Math.max(0, refinedT));
  6152. }
  6153. // Resolve cubic bezier for the given x
  6154. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6155. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6156. Math.pow(refinedT, 3);
  6157. };
  6158. return BezierCurve;
  6159. }());
  6160. BABYLON.BezierCurve = BezierCurve;
  6161. var Orientation;
  6162. (function (Orientation) {
  6163. Orientation[Orientation["CW"] = 0] = "CW";
  6164. Orientation[Orientation["CCW"] = 1] = "CCW";
  6165. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6166. var Angle = /** @class */ (function () {
  6167. /**
  6168. * Creates an Angle object of "radians" radians (float).
  6169. */
  6170. function Angle(radians) {
  6171. var _this = this;
  6172. /**
  6173. * Returns the Angle value in degrees (float).
  6174. */
  6175. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6176. /**
  6177. * Returns the Angle value in radians (float).
  6178. */
  6179. this.radians = function () { return _this._radians; };
  6180. this._radians = radians;
  6181. if (this._radians < 0.0)
  6182. this._radians += (2.0 * Math.PI);
  6183. }
  6184. /**
  6185. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6186. */
  6187. Angle.BetweenTwoPoints = function (a, b) {
  6188. var delta = b.subtract(a);
  6189. var theta = Math.atan2(delta.y, delta.x);
  6190. return new Angle(theta);
  6191. };
  6192. /**
  6193. * Returns a new Angle object from the passed float in radians.
  6194. */
  6195. Angle.FromRadians = function (radians) {
  6196. return new Angle(radians);
  6197. };
  6198. /**
  6199. * Returns a new Angle object from the passed float in degrees.
  6200. */
  6201. Angle.FromDegrees = function (degrees) {
  6202. return new Angle(degrees * Math.PI / 180.0);
  6203. };
  6204. return Angle;
  6205. }());
  6206. BABYLON.Angle = Angle;
  6207. var Arc2 = /** @class */ (function () {
  6208. /**
  6209. * Creates an Arc object from the three passed points : start, middle and end.
  6210. */
  6211. function Arc2(startPoint, midPoint, endPoint) {
  6212. this.startPoint = startPoint;
  6213. this.midPoint = midPoint;
  6214. this.endPoint = endPoint;
  6215. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6216. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6217. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6218. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6219. 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);
  6220. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6221. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6222. var a1 = this.startAngle.degrees();
  6223. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6224. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6225. // angles correction
  6226. if (a2 - a1 > +180.0)
  6227. a2 -= 360.0;
  6228. if (a2 - a1 < -180.0)
  6229. a2 += 360.0;
  6230. if (a3 - a2 > +180.0)
  6231. a3 -= 360.0;
  6232. if (a3 - a2 < -180.0)
  6233. a3 += 360.0;
  6234. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6235. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6236. }
  6237. return Arc2;
  6238. }());
  6239. BABYLON.Arc2 = Arc2;
  6240. var Path2 = /** @class */ (function () {
  6241. /**
  6242. * Creates a Path2 object from the starting 2D coordinates x and y.
  6243. */
  6244. function Path2(x, y) {
  6245. this._points = new Array();
  6246. this._length = 0.0;
  6247. this.closed = false;
  6248. this._points.push(new Vector2(x, y));
  6249. }
  6250. /**
  6251. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6252. * Returns the updated Path2.
  6253. */
  6254. Path2.prototype.addLineTo = function (x, y) {
  6255. if (this.closed) {
  6256. return this;
  6257. }
  6258. var newPoint = new Vector2(x, y);
  6259. var previousPoint = this._points[this._points.length - 1];
  6260. this._points.push(newPoint);
  6261. this._length += newPoint.subtract(previousPoint).length();
  6262. return this;
  6263. };
  6264. /**
  6265. * 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.
  6266. * Returns the updated Path2.
  6267. */
  6268. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6269. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6270. if (this.closed) {
  6271. return this;
  6272. }
  6273. var startPoint = this._points[this._points.length - 1];
  6274. var midPoint = new Vector2(midX, midY);
  6275. var endPoint = new Vector2(endX, endY);
  6276. var arc = new Arc2(startPoint, midPoint, endPoint);
  6277. var increment = arc.angle.radians() / numberOfSegments;
  6278. if (arc.orientation === Orientation.CW)
  6279. increment *= -1;
  6280. var currentAngle = arc.startAngle.radians() + increment;
  6281. for (var i = 0; i < numberOfSegments; i++) {
  6282. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6283. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6284. this.addLineTo(x, y);
  6285. currentAngle += increment;
  6286. }
  6287. return this;
  6288. };
  6289. /**
  6290. * Closes the Path2.
  6291. * Returns the Path2.
  6292. */
  6293. Path2.prototype.close = function () {
  6294. this.closed = true;
  6295. return this;
  6296. };
  6297. /**
  6298. * Returns the Path2 total length (float).
  6299. */
  6300. Path2.prototype.length = function () {
  6301. var result = this._length;
  6302. if (!this.closed) {
  6303. var lastPoint = this._points[this._points.length - 1];
  6304. var firstPoint = this._points[0];
  6305. result += (firstPoint.subtract(lastPoint).length());
  6306. }
  6307. return result;
  6308. };
  6309. /**
  6310. * Returns the Path2 internal array of points.
  6311. */
  6312. Path2.prototype.getPoints = function () {
  6313. return this._points;
  6314. };
  6315. /**
  6316. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6317. */
  6318. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6319. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6320. return Vector2.Zero();
  6321. }
  6322. var lengthPosition = normalizedLengthPosition * this.length();
  6323. var previousOffset = 0;
  6324. for (var i = 0; i < this._points.length; i++) {
  6325. var j = (i + 1) % this._points.length;
  6326. var a = this._points[i];
  6327. var b = this._points[j];
  6328. var bToA = b.subtract(a);
  6329. var nextOffset = (bToA.length() + previousOffset);
  6330. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6331. var dir = bToA.normalize();
  6332. var localOffset = lengthPosition - previousOffset;
  6333. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6334. }
  6335. previousOffset = nextOffset;
  6336. }
  6337. return Vector2.Zero();
  6338. };
  6339. /**
  6340. * Returns a new Path2 starting at the coordinates (x, y).
  6341. */
  6342. Path2.StartingAt = function (x, y) {
  6343. return new Path2(x, y);
  6344. };
  6345. return Path2;
  6346. }());
  6347. BABYLON.Path2 = Path2;
  6348. var Path3D = /** @class */ (function () {
  6349. /**
  6350. * new Path3D(path, normal, raw)
  6351. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6352. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6353. * path : an array of Vector3, the curve axis of the Path3D
  6354. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6355. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6356. */
  6357. function Path3D(path, firstNormal, raw) {
  6358. if (firstNormal === void 0) { firstNormal = null; }
  6359. this.path = path;
  6360. this._curve = new Array();
  6361. this._distances = new Array();
  6362. this._tangents = new Array();
  6363. this._normals = new Array();
  6364. this._binormals = new Array();
  6365. for (var p = 0; p < path.length; p++) {
  6366. this._curve[p] = path[p].clone(); // hard copy
  6367. }
  6368. this._raw = raw || false;
  6369. this._compute(firstNormal);
  6370. }
  6371. /**
  6372. * Returns the Path3D array of successive Vector3 designing its curve.
  6373. */
  6374. Path3D.prototype.getCurve = function () {
  6375. return this._curve;
  6376. };
  6377. /**
  6378. * Returns an array populated with tangent vectors on each Path3D curve point.
  6379. */
  6380. Path3D.prototype.getTangents = function () {
  6381. return this._tangents;
  6382. };
  6383. /**
  6384. * Returns an array populated with normal vectors on each Path3D curve point.
  6385. */
  6386. Path3D.prototype.getNormals = function () {
  6387. return this._normals;
  6388. };
  6389. /**
  6390. * Returns an array populated with binormal vectors on each Path3D curve point.
  6391. */
  6392. Path3D.prototype.getBinormals = function () {
  6393. return this._binormals;
  6394. };
  6395. /**
  6396. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6397. */
  6398. Path3D.prototype.getDistances = function () {
  6399. return this._distances;
  6400. };
  6401. /**
  6402. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6403. * Returns the same object updated.
  6404. */
  6405. Path3D.prototype.update = function (path, firstNormal) {
  6406. if (firstNormal === void 0) { firstNormal = null; }
  6407. for (var p = 0; p < path.length; p++) {
  6408. this._curve[p].x = path[p].x;
  6409. this._curve[p].y = path[p].y;
  6410. this._curve[p].z = path[p].z;
  6411. }
  6412. this._compute(firstNormal);
  6413. return this;
  6414. };
  6415. // private function compute() : computes tangents, normals and binormals
  6416. Path3D.prototype._compute = function (firstNormal) {
  6417. var l = this._curve.length;
  6418. // first and last tangents
  6419. this._tangents[0] = this._getFirstNonNullVector(0);
  6420. if (!this._raw) {
  6421. this._tangents[0].normalize();
  6422. }
  6423. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6424. if (!this._raw) {
  6425. this._tangents[l - 1].normalize();
  6426. }
  6427. // normals and binormals at first point : arbitrary vector with _normalVector()
  6428. var tg0 = this._tangents[0];
  6429. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6430. this._normals[0] = pp0;
  6431. if (!this._raw) {
  6432. this._normals[0].normalize();
  6433. }
  6434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6435. if (!this._raw) {
  6436. this._binormals[0].normalize();
  6437. }
  6438. this._distances[0] = 0.0;
  6439. // normals and binormals : next points
  6440. var prev; // previous vector (segment)
  6441. var cur; // current vector (segment)
  6442. var curTang; // current tangent
  6443. // previous normal
  6444. var prevBinor; // previous binormal
  6445. for (var i = 1; i < l; i++) {
  6446. // tangents
  6447. prev = this._getLastNonNullVector(i);
  6448. if (i < l - 1) {
  6449. cur = this._getFirstNonNullVector(i);
  6450. this._tangents[i] = prev.add(cur);
  6451. this._tangents[i].normalize();
  6452. }
  6453. this._distances[i] = this._distances[i - 1] + prev.length();
  6454. // normals and binormals
  6455. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6456. curTang = this._tangents[i];
  6457. prevBinor = this._binormals[i - 1];
  6458. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6459. if (!this._raw) {
  6460. this._normals[i].normalize();
  6461. }
  6462. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6463. if (!this._raw) {
  6464. this._binormals[i].normalize();
  6465. }
  6466. }
  6467. };
  6468. // private function getFirstNonNullVector(index)
  6469. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6470. Path3D.prototype._getFirstNonNullVector = function (index) {
  6471. var i = 1;
  6472. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6473. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6474. i++;
  6475. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6476. }
  6477. return nNVector;
  6478. };
  6479. // private function getLastNonNullVector(index)
  6480. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6481. Path3D.prototype._getLastNonNullVector = function (index) {
  6482. var i = 1;
  6483. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6484. while (nLVector.length() === 0 && index > i + 1) {
  6485. i++;
  6486. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6487. }
  6488. return nLVector;
  6489. };
  6490. // private function normalVector(v0, vt, va) :
  6491. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6492. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6493. Path3D.prototype._normalVector = function (v0, vt, va) {
  6494. var normal0;
  6495. var tgl = vt.length();
  6496. if (tgl === 0.0) {
  6497. tgl = 1.0;
  6498. }
  6499. if (va === undefined || va === null) {
  6500. var point;
  6501. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6502. point = new Vector3(0.0, -1.0, 0.0);
  6503. }
  6504. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6505. point = new Vector3(1.0, 0.0, 0.0);
  6506. }
  6507. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6508. point = new Vector3(0.0, 0.0, 1.0);
  6509. }
  6510. else {
  6511. point = Vector3.Zero();
  6512. }
  6513. normal0 = Vector3.Cross(vt, point);
  6514. }
  6515. else {
  6516. normal0 = Vector3.Cross(vt, va);
  6517. Vector3.CrossToRef(normal0, vt, normal0);
  6518. }
  6519. normal0.normalize();
  6520. return normal0;
  6521. };
  6522. return Path3D;
  6523. }());
  6524. BABYLON.Path3D = Path3D;
  6525. var Curve3 = /** @class */ (function () {
  6526. /**
  6527. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6528. * A Curve3 is designed from a series of successive Vector3.
  6529. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6530. */
  6531. function Curve3(points) {
  6532. this._length = 0.0;
  6533. this._points = points;
  6534. this._length = this._computeLength(points);
  6535. }
  6536. /**
  6537. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6538. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6539. * @param v1 (Vector3) the control point
  6540. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6541. * @param nbPoints (integer) the wanted number of points in the curve
  6542. */
  6543. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6544. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6545. var bez = new Array();
  6546. var equation = function (t, val0, val1, val2) {
  6547. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6548. return res;
  6549. };
  6550. for (var i = 0; i <= nbPoints; i++) {
  6551. 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)));
  6552. }
  6553. return new Curve3(bez);
  6554. };
  6555. /**
  6556. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6557. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6558. * @param v1 (Vector3) the first control point
  6559. * @param v2 (Vector3) the second control point
  6560. * @param v3 (Vector3) the end point of the Cubic Bezier
  6561. * @param nbPoints (integer) the wanted number of points in the curve
  6562. */
  6563. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6564. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6565. var bez = new Array();
  6566. var equation = function (t, val0, val1, val2, val3) {
  6567. 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;
  6568. return res;
  6569. };
  6570. for (var i = 0; i <= nbPoints; i++) {
  6571. 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)));
  6572. }
  6573. return new Curve3(bez);
  6574. };
  6575. /**
  6576. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6577. * @param p1 (Vector3) the origin point of the Hermite Spline
  6578. * @param t1 (Vector3) the tangent vector at the origin point
  6579. * @param p2 (Vector3) the end point of the Hermite Spline
  6580. * @param t2 (Vector3) the tangent vector at the end point
  6581. * @param nbPoints (integer) the wanted number of points in the curve
  6582. */
  6583. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6584. var hermite = new Array();
  6585. var step = 1.0 / nbPoints;
  6586. for (var i = 0; i <= nbPoints; i++) {
  6587. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6588. }
  6589. return new Curve3(hermite);
  6590. };
  6591. /**
  6592. * Returns a Curve3 object along a CatmullRom Spline curve :
  6593. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6594. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6595. */
  6596. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6597. var totalPoints = new Array();
  6598. totalPoints.push(points[0].clone());
  6599. Array.prototype.push.apply(totalPoints, points);
  6600. totalPoints.push(points[points.length - 1].clone());
  6601. var catmullRom = new Array();
  6602. var step = 1.0 / nbPoints;
  6603. var amount = 0.0;
  6604. for (var i = 0; i < totalPoints.length - 3; i++) {
  6605. amount = 0;
  6606. for (var c = 0; c < nbPoints; c++) {
  6607. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6608. amount += step;
  6609. }
  6610. }
  6611. i--;
  6612. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6613. return new Curve3(catmullRom);
  6614. };
  6615. /**
  6616. * Returns the Curve3 stored array of successive Vector3
  6617. */
  6618. Curve3.prototype.getPoints = function () {
  6619. return this._points;
  6620. };
  6621. /**
  6622. * Returns the computed length (float) of the curve.
  6623. */
  6624. Curve3.prototype.length = function () {
  6625. return this._length;
  6626. };
  6627. /**
  6628. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6629. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6630. * curveA and curveB keep unchanged.
  6631. */
  6632. Curve3.prototype.continue = function (curve) {
  6633. var lastPoint = this._points[this._points.length - 1];
  6634. var continuedPoints = this._points.slice();
  6635. var curvePoints = curve.getPoints();
  6636. for (var i = 1; i < curvePoints.length; i++) {
  6637. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6638. }
  6639. var continuedCurve = new Curve3(continuedPoints);
  6640. return continuedCurve;
  6641. };
  6642. Curve3.prototype._computeLength = function (path) {
  6643. var l = 0;
  6644. for (var i = 1; i < path.length; i++) {
  6645. l += (path[i].subtract(path[i - 1])).length();
  6646. }
  6647. return l;
  6648. };
  6649. return Curve3;
  6650. }());
  6651. BABYLON.Curve3 = Curve3;
  6652. // Vertex formats
  6653. var PositionNormalVertex = /** @class */ (function () {
  6654. function PositionNormalVertex(position, normal) {
  6655. if (position === void 0) { position = Vector3.Zero(); }
  6656. if (normal === void 0) { normal = Vector3.Up(); }
  6657. this.position = position;
  6658. this.normal = normal;
  6659. }
  6660. PositionNormalVertex.prototype.clone = function () {
  6661. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6662. };
  6663. return PositionNormalVertex;
  6664. }());
  6665. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6666. var PositionNormalTextureVertex = /** @class */ (function () {
  6667. function PositionNormalTextureVertex(position, normal, uv) {
  6668. if (position === void 0) { position = Vector3.Zero(); }
  6669. if (normal === void 0) { normal = Vector3.Up(); }
  6670. if (uv === void 0) { uv = Vector2.Zero(); }
  6671. this.position = position;
  6672. this.normal = normal;
  6673. this.uv = uv;
  6674. }
  6675. PositionNormalTextureVertex.prototype.clone = function () {
  6676. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6677. };
  6678. return PositionNormalTextureVertex;
  6679. }());
  6680. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6681. // Temporary pre-allocated objects for engine internal use
  6682. // usage in any internal function :
  6683. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6684. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6685. var Tmp = /** @class */ (function () {
  6686. function Tmp() {
  6687. }
  6688. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6689. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6690. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6691. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6692. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6693. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6694. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6695. Matrix.Zero(), Matrix.Zero(),
  6696. Matrix.Zero(), Matrix.Zero(),
  6697. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6698. return Tmp;
  6699. }());
  6700. BABYLON.Tmp = Tmp;
  6701. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6702. var MathTmp = /** @class */ (function () {
  6703. function MathTmp() {
  6704. }
  6705. MathTmp.Vector3 = [Vector3.Zero()];
  6706. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6707. MathTmp.Quaternion = [Quaternion.Zero()];
  6708. return MathTmp;
  6709. }());
  6710. })(BABYLON || (BABYLON = {}));
  6711. //# sourceMappingURL=babylon.math.js.map
  6712. var BABYLON;
  6713. (function (BABYLON) {
  6714. var Scalar = /** @class */ (function () {
  6715. function Scalar() {
  6716. }
  6717. /**
  6718. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6719. */
  6720. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6721. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6722. var num = a - b;
  6723. return -epsilon <= num && num <= epsilon;
  6724. };
  6725. /**
  6726. * Returns a string : the upper case translation of the number i to hexadecimal.
  6727. */
  6728. Scalar.ToHex = function (i) {
  6729. var str = i.toString(16);
  6730. if (i <= 15) {
  6731. return ("0" + str).toUpperCase();
  6732. }
  6733. return str.toUpperCase();
  6734. };
  6735. /**
  6736. * Returns -1 if value is negative and +1 is value is positive.
  6737. * Returns the value itself if it's equal to zero.
  6738. */
  6739. Scalar.Sign = function (value) {
  6740. value = +value; // convert to a number
  6741. if (value === 0 || isNaN(value))
  6742. return value;
  6743. return value > 0 ? 1 : -1;
  6744. };
  6745. /**
  6746. * Returns the value itself if it's between min and max.
  6747. * Returns min if the value is lower than min.
  6748. * Returns max if the value is greater than max.
  6749. */
  6750. Scalar.Clamp = function (value, min, max) {
  6751. if (min === void 0) { min = 0; }
  6752. if (max === void 0) { max = 1; }
  6753. return Math.min(max, Math.max(min, value));
  6754. };
  6755. /**
  6756. * Returns the log2 of value.
  6757. */
  6758. Scalar.Log2 = function (value) {
  6759. return Math.log(value) * Math.LOG2E;
  6760. };
  6761. /**
  6762. * Loops the value, so that it is never larger than length and never smaller than 0.
  6763. *
  6764. * This is similar to the modulo operator but it works with floating point numbers.
  6765. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6766. * With t = 5 and length = 2.5, the result would be 0.0.
  6767. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6768. */
  6769. Scalar.Repeat = function (value, length) {
  6770. return value - Math.floor(value / length) * length;
  6771. };
  6772. /**
  6773. * Normalize the value between 0.0 and 1.0 using min and max values
  6774. */
  6775. Scalar.Normalize = function (value, min, max) {
  6776. return (value - min) / (max - min);
  6777. };
  6778. /**
  6779. * Denormalize the value from 0.0 and 1.0 using min and max values
  6780. */
  6781. Scalar.Denormalize = function (normalized, min, max) {
  6782. return (normalized * (max - min) + min);
  6783. };
  6784. /**
  6785. * Calculates the shortest difference between two given angles given in degrees.
  6786. */
  6787. Scalar.DeltaAngle = function (current, target) {
  6788. var num = Scalar.Repeat(target - current, 360.0);
  6789. if (num > 180.0) {
  6790. num -= 360.0;
  6791. }
  6792. return num;
  6793. };
  6794. /**
  6795. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6796. *
  6797. * The returned value will move back and forth between 0 and length
  6798. */
  6799. Scalar.PingPong = function (tx, length) {
  6800. var t = Scalar.Repeat(tx, length * 2.0);
  6801. return length - Math.abs(t - length);
  6802. };
  6803. /**
  6804. * Interpolates between min and max with smoothing at the limits.
  6805. *
  6806. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6807. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6808. */
  6809. Scalar.SmoothStep = function (from, to, tx) {
  6810. var t = Scalar.Clamp(tx);
  6811. t = -2.0 * t * t * t + 3.0 * t * t;
  6812. return to * t + from * (1.0 - t);
  6813. };
  6814. /**
  6815. * Moves a value current towards target.
  6816. *
  6817. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6818. * Negative values of maxDelta pushes the value away from target.
  6819. */
  6820. Scalar.MoveTowards = function (current, target, maxDelta) {
  6821. var result = 0;
  6822. if (Math.abs(target - current) <= maxDelta) {
  6823. result = target;
  6824. }
  6825. else {
  6826. result = current + Scalar.Sign(target - current) * maxDelta;
  6827. }
  6828. return result;
  6829. };
  6830. /**
  6831. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6832. *
  6833. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6834. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6835. */
  6836. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6837. var num = Scalar.DeltaAngle(current, target);
  6838. var result = 0;
  6839. if (-maxDelta < num && num < maxDelta) {
  6840. result = target;
  6841. }
  6842. else {
  6843. target = current + num;
  6844. result = Scalar.MoveTowards(current, target, maxDelta);
  6845. }
  6846. return result;
  6847. };
  6848. /**
  6849. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6850. */
  6851. Scalar.Lerp = function (start, end, amount) {
  6852. return start + ((end - start) * amount);
  6853. };
  6854. /**
  6855. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6856. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6857. */
  6858. Scalar.LerpAngle = function (start, end, amount) {
  6859. var num = Scalar.Repeat(end - start, 360.0);
  6860. if (num > 180.0) {
  6861. num -= 360.0;
  6862. }
  6863. return start + num * Scalar.Clamp(amount);
  6864. };
  6865. /**
  6866. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6867. */
  6868. Scalar.InverseLerp = function (a, b, value) {
  6869. var result = 0;
  6870. if (a != b) {
  6871. result = Scalar.Clamp((value - a) / (b - a));
  6872. }
  6873. else {
  6874. result = 0.0;
  6875. }
  6876. return result;
  6877. };
  6878. /**
  6879. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6880. */
  6881. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6882. var squared = amount * amount;
  6883. var cubed = amount * squared;
  6884. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6885. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6886. var part3 = (cubed - (2.0 * squared)) + amount;
  6887. var part4 = cubed - squared;
  6888. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6889. };
  6890. /**
  6891. * Returns a random float number between and min and max values
  6892. */
  6893. Scalar.RandomRange = function (min, max) {
  6894. if (min === max)
  6895. return min;
  6896. return ((Math.random() * (max - min)) + min);
  6897. };
  6898. /**
  6899. * This function returns percentage of a number in a given range.
  6900. *
  6901. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6902. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6903. */
  6904. Scalar.RangeToPercent = function (number, min, max) {
  6905. return ((number - min) / (max - min));
  6906. };
  6907. /**
  6908. * This function returns number that corresponds to the percentage in a given range.
  6909. *
  6910. * PercentToRange(0.34,0,100) will return 34.
  6911. */
  6912. Scalar.PercentToRange = function (percent, min, max) {
  6913. return ((max - min) * percent + min);
  6914. };
  6915. /**
  6916. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6917. * @param angle The angle to normalize in radian.
  6918. * @return The converted angle.
  6919. */
  6920. Scalar.NormalizeRadians = function (angle) {
  6921. // More precise but slower version kept for reference.
  6922. // angle = angle % Tools.TwoPi;
  6923. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6924. //if (angle > Math.PI) {
  6925. // angle -= Tools.TwoPi;
  6926. //}
  6927. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6928. return angle;
  6929. };
  6930. /**
  6931. * Two pi constants convenient for computation.
  6932. */
  6933. Scalar.TwoPi = Math.PI * 2;
  6934. return Scalar;
  6935. }());
  6936. BABYLON.Scalar = Scalar;
  6937. })(BABYLON || (BABYLON = {}));
  6938. //# sourceMappingURL=babylon.math.scalar.js.map
  6939. //# sourceMappingURL=babylon.mixins.js.map
  6940. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6941. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6942. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6943. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6944. //# sourceMappingURL=babylon.webgl2.js.map
  6945. var BABYLON;
  6946. (function (BABYLON) {
  6947. var __decoratorInitialStore = {};
  6948. var __mergedStore = {};
  6949. var _copySource = function (creationFunction, source, instanciate) {
  6950. var destination = creationFunction();
  6951. // Tags
  6952. if (BABYLON.Tags) {
  6953. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6954. }
  6955. var classStore = getMergedStore(destination);
  6956. // Properties
  6957. for (var property in classStore) {
  6958. var propertyDescriptor = classStore[property];
  6959. var sourceProperty = source[property];
  6960. var propertyType = propertyDescriptor.type;
  6961. if (sourceProperty !== undefined && sourceProperty !== null) {
  6962. switch (propertyType) {
  6963. case 0: // Value
  6964. case 6:// Mesh reference
  6965. destination[property] = sourceProperty;
  6966. break;
  6967. case 1:// Texture
  6968. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6969. break;
  6970. case 2: // Color3
  6971. case 3: // FresnelParameters
  6972. case 4: // Vector2
  6973. case 5: // Vector3
  6974. case 7: // Color Curves
  6975. case 10:// Quaternion
  6976. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6977. break;
  6978. }
  6979. }
  6980. }
  6981. return destination;
  6982. };
  6983. function getDirectStore(target) {
  6984. var classKey = target.getClassName();
  6985. if (!__decoratorInitialStore[classKey]) {
  6986. __decoratorInitialStore[classKey] = {};
  6987. }
  6988. return __decoratorInitialStore[classKey];
  6989. }
  6990. /**
  6991. * Return the list of properties flagged as serializable
  6992. * @param target: host object
  6993. */
  6994. function getMergedStore(target) {
  6995. var classKey = target.getClassName();
  6996. if (__mergedStore[classKey]) {
  6997. return __mergedStore[classKey];
  6998. }
  6999. __mergedStore[classKey] = {};
  7000. var store = __mergedStore[classKey];
  7001. var currentTarget = target;
  7002. var currentKey = classKey;
  7003. while (currentKey) {
  7004. var initialStore = __decoratorInitialStore[currentKey];
  7005. for (var property in initialStore) {
  7006. store[property] = initialStore[property];
  7007. }
  7008. var parent_1 = void 0;
  7009. var done = false;
  7010. do {
  7011. parent_1 = Object.getPrototypeOf(currentTarget);
  7012. if (!parent_1.getClassName) {
  7013. done = true;
  7014. break;
  7015. }
  7016. if (parent_1.getClassName() !== currentKey) {
  7017. break;
  7018. }
  7019. currentTarget = parent_1;
  7020. } while (parent_1);
  7021. if (done) {
  7022. break;
  7023. }
  7024. currentKey = parent_1.getClassName();
  7025. currentTarget = parent_1;
  7026. }
  7027. return store;
  7028. }
  7029. function generateSerializableMember(type, sourceName) {
  7030. return function (target, propertyKey) {
  7031. var classStore = getDirectStore(target);
  7032. if (!classStore[propertyKey]) {
  7033. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7034. }
  7035. };
  7036. }
  7037. function generateExpandMember(setCallback, targetKey) {
  7038. if (targetKey === void 0) { targetKey = null; }
  7039. return function (target, propertyKey) {
  7040. var key = targetKey || ("_" + propertyKey);
  7041. Object.defineProperty(target, propertyKey, {
  7042. get: function () {
  7043. return this[key];
  7044. },
  7045. set: function (value) {
  7046. if (this[key] === value) {
  7047. return;
  7048. }
  7049. this[key] = value;
  7050. target[setCallback].apply(this);
  7051. },
  7052. enumerable: true,
  7053. configurable: true
  7054. });
  7055. };
  7056. }
  7057. function expandToProperty(callback, targetKey) {
  7058. if (targetKey === void 0) { targetKey = null; }
  7059. return generateExpandMember(callback, targetKey);
  7060. }
  7061. BABYLON.expandToProperty = expandToProperty;
  7062. function serialize(sourceName) {
  7063. return generateSerializableMember(0, sourceName); // value member
  7064. }
  7065. BABYLON.serialize = serialize;
  7066. function serializeAsTexture(sourceName) {
  7067. return generateSerializableMember(1, sourceName); // texture member
  7068. }
  7069. BABYLON.serializeAsTexture = serializeAsTexture;
  7070. function serializeAsColor3(sourceName) {
  7071. return generateSerializableMember(2, sourceName); // color3 member
  7072. }
  7073. BABYLON.serializeAsColor3 = serializeAsColor3;
  7074. function serializeAsFresnelParameters(sourceName) {
  7075. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7076. }
  7077. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7078. function serializeAsVector2(sourceName) {
  7079. return generateSerializableMember(4, sourceName); // vector2 member
  7080. }
  7081. BABYLON.serializeAsVector2 = serializeAsVector2;
  7082. function serializeAsVector3(sourceName) {
  7083. return generateSerializableMember(5, sourceName); // vector3 member
  7084. }
  7085. BABYLON.serializeAsVector3 = serializeAsVector3;
  7086. function serializeAsMeshReference(sourceName) {
  7087. return generateSerializableMember(6, sourceName); // mesh reference member
  7088. }
  7089. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7090. function serializeAsColorCurves(sourceName) {
  7091. return generateSerializableMember(7, sourceName); // color curves
  7092. }
  7093. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7094. function serializeAsColor4(sourceName) {
  7095. return generateSerializableMember(8, sourceName); // color 4
  7096. }
  7097. BABYLON.serializeAsColor4 = serializeAsColor4;
  7098. function serializeAsImageProcessingConfiguration(sourceName) {
  7099. return generateSerializableMember(9, sourceName); // image processing
  7100. }
  7101. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7102. function serializeAsQuaternion(sourceName) {
  7103. return generateSerializableMember(10, sourceName); // quaternion member
  7104. }
  7105. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7106. var SerializationHelper = /** @class */ (function () {
  7107. function SerializationHelper() {
  7108. }
  7109. SerializationHelper.Serialize = function (entity, serializationObject) {
  7110. if (!serializationObject) {
  7111. serializationObject = {};
  7112. }
  7113. // Tags
  7114. if (BABYLON.Tags) {
  7115. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7116. }
  7117. var serializedProperties = getMergedStore(entity);
  7118. // Properties
  7119. for (var property in serializedProperties) {
  7120. var propertyDescriptor = serializedProperties[property];
  7121. var targetPropertyName = propertyDescriptor.sourceName || property;
  7122. var propertyType = propertyDescriptor.type;
  7123. var sourceProperty = entity[property];
  7124. if (sourceProperty !== undefined && sourceProperty !== null) {
  7125. switch (propertyType) {
  7126. case 0:// Value
  7127. serializationObject[targetPropertyName] = sourceProperty;
  7128. break;
  7129. case 1:// Texture
  7130. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7131. break;
  7132. case 2:// Color3
  7133. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7134. break;
  7135. case 3:// FresnelParameters
  7136. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7137. break;
  7138. case 4:// Vector2
  7139. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7140. break;
  7141. case 5:// Vector3
  7142. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7143. break;
  7144. case 6:// Mesh reference
  7145. serializationObject[targetPropertyName] = sourceProperty.id;
  7146. break;
  7147. case 7:// Color Curves
  7148. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7149. break;
  7150. case 8:// Color 4
  7151. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7152. break;
  7153. case 9:// Image Processing
  7154. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7155. break;
  7156. }
  7157. }
  7158. }
  7159. return serializationObject;
  7160. };
  7161. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7162. if (rootUrl === void 0) { rootUrl = null; }
  7163. var destination = creationFunction();
  7164. if (!rootUrl) {
  7165. rootUrl = "";
  7166. }
  7167. // Tags
  7168. if (BABYLON.Tags) {
  7169. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7170. }
  7171. var classStore = getMergedStore(destination);
  7172. // Properties
  7173. for (var property in classStore) {
  7174. var propertyDescriptor = classStore[property];
  7175. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7176. var propertyType = propertyDescriptor.type;
  7177. if (sourceProperty !== undefined && sourceProperty !== null) {
  7178. var dest = destination;
  7179. switch (propertyType) {
  7180. case 0:// Value
  7181. dest[property] = sourceProperty;
  7182. break;
  7183. case 1:// Texture
  7184. if (scene) {
  7185. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7186. }
  7187. break;
  7188. case 2:// Color3
  7189. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7190. break;
  7191. case 3:// FresnelParameters
  7192. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7193. break;
  7194. case 4:// Vector2
  7195. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7196. break;
  7197. case 5:// Vector3
  7198. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7199. break;
  7200. case 6:// Mesh reference
  7201. if (scene) {
  7202. dest[property] = scene.getLastMeshByID(sourceProperty);
  7203. }
  7204. break;
  7205. case 7:// Color Curves
  7206. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7207. break;
  7208. case 8:// Color 4
  7209. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7210. break;
  7211. case 9:// Image Processing
  7212. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7213. break;
  7214. }
  7215. }
  7216. }
  7217. return destination;
  7218. };
  7219. SerializationHelper.Clone = function (creationFunction, source) {
  7220. return _copySource(creationFunction, source, false);
  7221. };
  7222. SerializationHelper.Instanciate = function (creationFunction, source) {
  7223. return _copySource(creationFunction, source, true);
  7224. };
  7225. return SerializationHelper;
  7226. }());
  7227. BABYLON.SerializationHelper = SerializationHelper;
  7228. })(BABYLON || (BABYLON = {}));
  7229. //# sourceMappingURL=babylon.decorators.js.map
  7230. var BABYLON;
  7231. (function (BABYLON) {
  7232. /**
  7233. * Wrapper class for promise with external resolve and reject.
  7234. */
  7235. var Deferred = /** @class */ (function () {
  7236. /**
  7237. * Constructor for this deferred object.
  7238. */
  7239. function Deferred() {
  7240. var _this = this;
  7241. this.promise = new Promise(function (resolve, reject) {
  7242. _this._resolve = resolve;
  7243. _this._reject = reject;
  7244. });
  7245. }
  7246. Object.defineProperty(Deferred.prototype, "resolve", {
  7247. /**
  7248. * The resolve method of the promise associated with this deferred object.
  7249. */
  7250. get: function () {
  7251. return this._resolve;
  7252. },
  7253. enumerable: true,
  7254. configurable: true
  7255. });
  7256. Object.defineProperty(Deferred.prototype, "reject", {
  7257. /**
  7258. * The reject method of the promise associated with this deferred object.
  7259. */
  7260. get: function () {
  7261. return this._reject;
  7262. },
  7263. enumerable: true,
  7264. configurable: true
  7265. });
  7266. return Deferred;
  7267. }());
  7268. BABYLON.Deferred = Deferred;
  7269. })(BABYLON || (BABYLON = {}));
  7270. //# sourceMappingURL=babylon.deferred.js.map
  7271. var BABYLON;
  7272. (function (BABYLON) {
  7273. /**
  7274. * A class serves as a medium between the observable and its observers
  7275. */
  7276. var EventState = /** @class */ (function () {
  7277. /**
  7278. * Create a new EventState
  7279. * @param mask defines the mask associated with this state
  7280. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7281. * @param target defines the original target of the state
  7282. * @param currentTarget defines the current target of the state
  7283. */
  7284. function EventState(mask, skipNextObservers, target, currentTarget) {
  7285. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7286. this.initalize(mask, skipNextObservers, target, currentTarget);
  7287. }
  7288. /**
  7289. * Initialize the current event state
  7290. * @param mask defines the mask associated with this state
  7291. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7292. * @param target defines the original target of the state
  7293. * @param currentTarget defines the current target of the state
  7294. * @returns the current event state
  7295. */
  7296. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7297. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7298. this.mask = mask;
  7299. this.skipNextObservers = skipNextObservers;
  7300. this.target = target;
  7301. this.currentTarget = currentTarget;
  7302. return this;
  7303. };
  7304. return EventState;
  7305. }());
  7306. BABYLON.EventState = EventState;
  7307. /**
  7308. * Represent an Observer registered to a given Observable object.
  7309. */
  7310. var Observer = /** @class */ (function () {
  7311. /**
  7312. * Creates a new observer
  7313. * @param callback defines the callback to call when the observer is notified
  7314. * @param mask defines the mask of the observer (used to filter notifications)
  7315. * @param scope defines the current scope used to restore the JS context
  7316. */
  7317. function Observer(
  7318. /**
  7319. * Defines the callback to call when the observer is notified
  7320. */
  7321. callback,
  7322. /**
  7323. * Defines the mask of the observer (used to filter notifications)
  7324. */
  7325. mask,
  7326. /**
  7327. * Defines the current scope used to restore the JS context
  7328. */
  7329. scope) {
  7330. if (scope === void 0) { scope = null; }
  7331. this.callback = callback;
  7332. this.mask = mask;
  7333. this.scope = scope;
  7334. /** @ignore */
  7335. this._willBeUnregistered = false;
  7336. /**
  7337. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7338. */
  7339. this.unregisterOnNextCall = false;
  7340. }
  7341. return Observer;
  7342. }());
  7343. BABYLON.Observer = Observer;
  7344. /**
  7345. * Represent a list of observers registered to multiple Observables object.
  7346. */
  7347. var MultiObserver = /** @class */ (function () {
  7348. function MultiObserver() {
  7349. }
  7350. /**
  7351. * Release associated resources
  7352. */
  7353. MultiObserver.prototype.dispose = function () {
  7354. if (this._observers && this._observables) {
  7355. for (var index = 0; index < this._observers.length; index++) {
  7356. this._observables[index].remove(this._observers[index]);
  7357. }
  7358. }
  7359. this._observers = null;
  7360. this._observables = null;
  7361. };
  7362. /**
  7363. * Raise a callback when one of the observable will notify
  7364. * @param observables defines a list of observables to watch
  7365. * @param callback defines the callback to call on notification
  7366. * @param mask defines the mask used to filter notifications
  7367. * @param scope defines the current scope used to restore the JS context
  7368. * @returns the new MultiObserver
  7369. */
  7370. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7371. if (mask === void 0) { mask = -1; }
  7372. if (scope === void 0) { scope = null; }
  7373. var result = new MultiObserver();
  7374. result._observers = new Array();
  7375. result._observables = observables;
  7376. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7377. var observable = observables_1[_i];
  7378. var observer = observable.add(callback, mask, false, scope);
  7379. if (observer) {
  7380. result._observers.push(observer);
  7381. }
  7382. }
  7383. return result;
  7384. };
  7385. return MultiObserver;
  7386. }());
  7387. BABYLON.MultiObserver = MultiObserver;
  7388. /**
  7389. * The Observable class is a simple implementation of the Observable pattern.
  7390. * 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.
  7391. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7392. * 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).
  7393. * 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.
  7394. */
  7395. var Observable = /** @class */ (function () {
  7396. /**
  7397. * Creates a new observable
  7398. * @param onObserverAdded defines a callback to call when a new observer is added
  7399. */
  7400. function Observable(onObserverAdded) {
  7401. this._observers = new Array();
  7402. this._eventState = new EventState(0);
  7403. if (onObserverAdded) {
  7404. this._onObserverAdded = onObserverAdded;
  7405. }
  7406. }
  7407. /**
  7408. * Create a new Observer with the specified callback
  7409. * @param callback the callback that will be executed for that Observer
  7410. * @param mask the mask used to filter observers
  7411. * @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.
  7412. * @param scope optional scope for the callback to be called from
  7413. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7414. * @returns the new observer created for the callback
  7415. */
  7416. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7417. if (mask === void 0) { mask = -1; }
  7418. if (insertFirst === void 0) { insertFirst = false; }
  7419. if (scope === void 0) { scope = null; }
  7420. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7421. if (!callback) {
  7422. return null;
  7423. }
  7424. var observer = new Observer(callback, mask, scope);
  7425. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7426. if (insertFirst) {
  7427. this._observers.unshift(observer);
  7428. }
  7429. else {
  7430. this._observers.push(observer);
  7431. }
  7432. if (this._onObserverAdded) {
  7433. this._onObserverAdded(observer);
  7434. }
  7435. return observer;
  7436. };
  7437. /**
  7438. * Remove an Observer from the Observable object
  7439. * @param observer the instance of the Observer to remove
  7440. * @returns false if it doesn't belong to this Observable
  7441. */
  7442. Observable.prototype.remove = function (observer) {
  7443. if (!observer) {
  7444. return false;
  7445. }
  7446. var index = this._observers.indexOf(observer);
  7447. if (index !== -1) {
  7448. this._observers.splice(index, 1);
  7449. return true;
  7450. }
  7451. return false;
  7452. };
  7453. /**
  7454. * Remove a callback from the Observable object
  7455. * @param callback the callback to remove
  7456. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7457. * @returns false if it doesn't belong to this Observable
  7458. */
  7459. Observable.prototype.removeCallback = function (callback, scope) {
  7460. for (var index = 0; index < this._observers.length; index++) {
  7461. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7462. this._observers.splice(index, 1);
  7463. return true;
  7464. }
  7465. }
  7466. return false;
  7467. };
  7468. Observable.prototype._deferUnregister = function (observer) {
  7469. var _this = this;
  7470. observer.unregisterOnNextCall = false;
  7471. observer._willBeUnregistered = true;
  7472. BABYLON.Tools.SetImmediate(function () {
  7473. _this.remove(observer);
  7474. });
  7475. };
  7476. /**
  7477. * Notify all Observers by calling their respective callback with the given data
  7478. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7479. * @param eventData defines the data to send to all observers
  7480. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7481. * @param target defines the original target of the state
  7482. * @param currentTarget defines the current target of the state
  7483. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7484. */
  7485. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7486. if (mask === void 0) { mask = -1; }
  7487. if (!this._observers.length) {
  7488. return true;
  7489. }
  7490. var state = this._eventState;
  7491. state.mask = mask;
  7492. state.target = target;
  7493. state.currentTarget = currentTarget;
  7494. state.skipNextObservers = false;
  7495. state.lastReturnValue = eventData;
  7496. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7497. var obs = _a[_i];
  7498. if (obs._willBeUnregistered) {
  7499. continue;
  7500. }
  7501. if (obs.mask & mask) {
  7502. if (obs.scope) {
  7503. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7504. }
  7505. else {
  7506. state.lastReturnValue = obs.callback(eventData, state);
  7507. }
  7508. if (obs.unregisterOnNextCall) {
  7509. this._deferUnregister(obs);
  7510. }
  7511. }
  7512. if (state.skipNextObservers) {
  7513. return false;
  7514. }
  7515. }
  7516. return true;
  7517. };
  7518. /**
  7519. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7520. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7521. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7522. * and it is crucial that all callbacks will be executed.
  7523. * The order of the callbacks is kept, callbacks are not executed parallel.
  7524. *
  7525. * @param eventData The data to be sent to each callback
  7526. * @param mask is used to filter observers defaults to -1
  7527. * @param target defines the callback target (see EventState)
  7528. * @param currentTarget defines he current object in the bubbling phase
  7529. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7530. */
  7531. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7532. var _this = this;
  7533. if (mask === void 0) { mask = -1; }
  7534. // create an empty promise
  7535. var p = Promise.resolve(eventData);
  7536. // no observers? return this promise.
  7537. if (!this._observers.length) {
  7538. return p;
  7539. }
  7540. var state = this._eventState;
  7541. state.mask = mask;
  7542. state.target = target;
  7543. state.currentTarget = currentTarget;
  7544. state.skipNextObservers = false;
  7545. // execute one callback after another (not using Promise.all, the order is important)
  7546. this._observers.forEach(function (obs) {
  7547. if (state.skipNextObservers) {
  7548. return;
  7549. }
  7550. if (obs._willBeUnregistered) {
  7551. return;
  7552. }
  7553. if (obs.mask & mask) {
  7554. if (obs.scope) {
  7555. p = p.then(function (lastReturnedValue) {
  7556. state.lastReturnValue = lastReturnedValue;
  7557. return obs.callback.apply(obs.scope, [eventData, state]);
  7558. });
  7559. }
  7560. else {
  7561. p = p.then(function (lastReturnedValue) {
  7562. state.lastReturnValue = lastReturnedValue;
  7563. return obs.callback(eventData, state);
  7564. });
  7565. }
  7566. if (obs.unregisterOnNextCall) {
  7567. _this._deferUnregister(obs);
  7568. }
  7569. }
  7570. });
  7571. // return the eventData
  7572. return p.then(function () { return eventData; });
  7573. };
  7574. /**
  7575. * Notify a specific observer
  7576. * @param observer defines the observer to notify
  7577. * @param eventData defines the data to be sent to each callback
  7578. * @param mask is used to filter observers defaults to -1
  7579. */
  7580. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7581. if (mask === void 0) { mask = -1; }
  7582. var state = this._eventState;
  7583. state.mask = mask;
  7584. state.skipNextObservers = false;
  7585. observer.callback(eventData, state);
  7586. };
  7587. /**
  7588. * Gets a boolean indicating if the observable has at least one observer
  7589. * @returns true is the Observable has at least one Observer registered
  7590. */
  7591. Observable.prototype.hasObservers = function () {
  7592. return this._observers.length > 0;
  7593. };
  7594. /**
  7595. * Clear the list of observers
  7596. */
  7597. Observable.prototype.clear = function () {
  7598. this._observers = new Array();
  7599. this._onObserverAdded = null;
  7600. };
  7601. /**
  7602. * Clone the current observable
  7603. * @returns a new observable
  7604. */
  7605. Observable.prototype.clone = function () {
  7606. var result = new Observable();
  7607. result._observers = this._observers.slice(0);
  7608. return result;
  7609. };
  7610. /**
  7611. * Does this observable handles observer registered with a given mask
  7612. * @param mask defines the mask to be tested
  7613. * @return whether or not one observer registered with the given mask is handeled
  7614. **/
  7615. Observable.prototype.hasSpecificMask = function (mask) {
  7616. if (mask === void 0) { mask = -1; }
  7617. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7618. var obs = _a[_i];
  7619. if (obs.mask & mask || obs.mask === mask) {
  7620. return true;
  7621. }
  7622. }
  7623. return false;
  7624. };
  7625. return Observable;
  7626. }());
  7627. BABYLON.Observable = Observable;
  7628. })(BABYLON || (BABYLON = {}));
  7629. //# sourceMappingURL=babylon.observable.js.map
  7630. var BABYLON;
  7631. (function (BABYLON) {
  7632. var SmartArray = /** @class */ (function () {
  7633. function SmartArray(capacity) {
  7634. this.length = 0;
  7635. this.data = new Array(capacity);
  7636. this._id = SmartArray._GlobalId++;
  7637. }
  7638. SmartArray.prototype.push = function (value) {
  7639. this.data[this.length++] = value;
  7640. if (this.length > this.data.length) {
  7641. this.data.length *= 2;
  7642. }
  7643. };
  7644. SmartArray.prototype.forEach = function (func) {
  7645. for (var index = 0; index < this.length; index++) {
  7646. func(this.data[index]);
  7647. }
  7648. };
  7649. SmartArray.prototype.sort = function (compareFn) {
  7650. this.data.sort(compareFn);
  7651. };
  7652. SmartArray.prototype.reset = function () {
  7653. this.length = 0;
  7654. };
  7655. SmartArray.prototype.dispose = function () {
  7656. this.reset();
  7657. if (this.data) {
  7658. this.data.length = 0;
  7659. this.data = [];
  7660. }
  7661. };
  7662. SmartArray.prototype.concat = function (array) {
  7663. if (array.length === 0) {
  7664. return;
  7665. }
  7666. if (this.length + array.length > this.data.length) {
  7667. this.data.length = (this.length + array.length) * 2;
  7668. }
  7669. for (var index = 0; index < array.length; index++) {
  7670. this.data[this.length++] = (array.data || array)[index];
  7671. }
  7672. };
  7673. SmartArray.prototype.indexOf = function (value) {
  7674. var position = this.data.indexOf(value);
  7675. if (position >= this.length) {
  7676. return -1;
  7677. }
  7678. return position;
  7679. };
  7680. SmartArray.prototype.contains = function (value) {
  7681. return this.data.indexOf(value) !== -1;
  7682. };
  7683. // Statics
  7684. SmartArray._GlobalId = 0;
  7685. return SmartArray;
  7686. }());
  7687. BABYLON.SmartArray = SmartArray;
  7688. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7689. __extends(SmartArrayNoDuplicate, _super);
  7690. function SmartArrayNoDuplicate() {
  7691. var _this = _super !== null && _super.apply(this, arguments) || this;
  7692. _this._duplicateId = 0;
  7693. return _this;
  7694. }
  7695. SmartArrayNoDuplicate.prototype.push = function (value) {
  7696. _super.prototype.push.call(this, value);
  7697. if (!value.__smartArrayFlags) {
  7698. value.__smartArrayFlags = {};
  7699. }
  7700. value.__smartArrayFlags[this._id] = this._duplicateId;
  7701. };
  7702. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7703. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7704. return false;
  7705. }
  7706. this.push(value);
  7707. return true;
  7708. };
  7709. SmartArrayNoDuplicate.prototype.reset = function () {
  7710. _super.prototype.reset.call(this);
  7711. this._duplicateId++;
  7712. };
  7713. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7714. if (array.length === 0) {
  7715. return;
  7716. }
  7717. if (this.length + array.length > this.data.length) {
  7718. this.data.length = (this.length + array.length) * 2;
  7719. }
  7720. for (var index = 0; index < array.length; index++) {
  7721. var item = (array.data || array)[index];
  7722. this.pushNoDuplicate(item);
  7723. }
  7724. };
  7725. return SmartArrayNoDuplicate;
  7726. }(SmartArray));
  7727. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7728. })(BABYLON || (BABYLON = {}));
  7729. //# sourceMappingURL=babylon.smartArray.js.map
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7733. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7734. var LoadFileError = /** @class */ (function (_super) {
  7735. __extends(LoadFileError, _super);
  7736. function LoadFileError(message, request) {
  7737. var _this = _super.call(this, message) || this;
  7738. _this.request = request;
  7739. _this.name = "LoadFileError";
  7740. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7741. return _this;
  7742. }
  7743. // Polyfill for Object.setPrototypeOf if necessary.
  7744. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7745. return LoadFileError;
  7746. }(Error));
  7747. BABYLON.LoadFileError = LoadFileError;
  7748. var RetryStrategy = /** @class */ (function () {
  7749. function RetryStrategy() {
  7750. }
  7751. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7752. if (maxRetries === void 0) { maxRetries = 3; }
  7753. if (baseInterval === void 0) { baseInterval = 500; }
  7754. return function (url, request, retryIndex) {
  7755. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7756. return -1;
  7757. }
  7758. return Math.pow(2, retryIndex) * baseInterval;
  7759. };
  7760. };
  7761. return RetryStrategy;
  7762. }());
  7763. BABYLON.RetryStrategy = RetryStrategy;
  7764. // Screenshots
  7765. var screenshotCanvas;
  7766. var cloneValue = function (source, destinationObject) {
  7767. if (!source)
  7768. return null;
  7769. if (source instanceof BABYLON.Mesh) {
  7770. return null;
  7771. }
  7772. if (source instanceof BABYLON.SubMesh) {
  7773. return source.clone(destinationObject);
  7774. }
  7775. else if (source.clone) {
  7776. return source.clone();
  7777. }
  7778. return null;
  7779. };
  7780. var Tools = /** @class */ (function () {
  7781. function Tools() {
  7782. }
  7783. /**
  7784. * Interpolates between a and b via alpha
  7785. * @param a The lower value (returned when alpha = 0)
  7786. * @param b The upper value (returned when alpha = 1)
  7787. * @param alpha The interpolation-factor
  7788. * @return The mixed value
  7789. */
  7790. Tools.Mix = function (a, b, alpha) {
  7791. return a * (1 - alpha) + b * alpha;
  7792. };
  7793. Tools.Instantiate = function (className) {
  7794. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7795. return Tools.RegisteredExternalClasses[className];
  7796. }
  7797. var arr = className.split(".");
  7798. var fn = (window || this);
  7799. for (var i = 0, len = arr.length; i < len; i++) {
  7800. fn = fn[arr[i]];
  7801. }
  7802. if (typeof fn !== "function") {
  7803. return null;
  7804. }
  7805. return fn;
  7806. };
  7807. /**
  7808. * Provides a slice function that will work even on IE
  7809. * @param data defines the array to slice
  7810. * @returns the new sliced array
  7811. */
  7812. Tools.Slice = function (data) {
  7813. if (data.slice) {
  7814. return data.slice();
  7815. }
  7816. return Array.prototype.slice.call(data);
  7817. };
  7818. Tools.SetImmediate = function (action) {
  7819. if (window.setImmediate) {
  7820. window.setImmediate(action);
  7821. }
  7822. else {
  7823. setTimeout(action, 1);
  7824. }
  7825. };
  7826. Tools.IsExponentOfTwo = function (value) {
  7827. var count = 1;
  7828. do {
  7829. count *= 2;
  7830. } while (count < value);
  7831. return count === value;
  7832. };
  7833. /**
  7834. * Find the next highest power of two.
  7835. * @param x Number to start search from.
  7836. * @return Next highest power of two.
  7837. */
  7838. Tools.CeilingPOT = function (x) {
  7839. x--;
  7840. x |= x >> 1;
  7841. x |= x >> 2;
  7842. x |= x >> 4;
  7843. x |= x >> 8;
  7844. x |= x >> 16;
  7845. x++;
  7846. return x;
  7847. };
  7848. /**
  7849. * Find the next lowest power of two.
  7850. * @param x Number to start search from.
  7851. * @return Next lowest power of two.
  7852. */
  7853. Tools.FloorPOT = function (x) {
  7854. x = x | (x >> 1);
  7855. x = x | (x >> 2);
  7856. x = x | (x >> 4);
  7857. x = x | (x >> 8);
  7858. x = x | (x >> 16);
  7859. return x - (x >> 1);
  7860. };
  7861. /**
  7862. * Find the nearest power of two.
  7863. * @param x Number to start search from.
  7864. * @return Next nearest power of two.
  7865. */
  7866. Tools.NearestPOT = function (x) {
  7867. var c = Tools.CeilingPOT(x);
  7868. var f = Tools.FloorPOT(x);
  7869. return (c - x) > (x - f) ? f : c;
  7870. };
  7871. Tools.GetExponentOfTwo = function (value, max, mode) {
  7872. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7873. var pot;
  7874. switch (mode) {
  7875. case BABYLON.Engine.SCALEMODE_FLOOR:
  7876. pot = Tools.FloorPOT(value);
  7877. break;
  7878. case BABYLON.Engine.SCALEMODE_NEAREST:
  7879. pot = Tools.NearestPOT(value);
  7880. break;
  7881. case BABYLON.Engine.SCALEMODE_CEILING:
  7882. default:
  7883. pot = Tools.CeilingPOT(value);
  7884. break;
  7885. }
  7886. return Math.min(pot, max);
  7887. };
  7888. Tools.GetFilename = function (path) {
  7889. var index = path.lastIndexOf("/");
  7890. if (index < 0)
  7891. return path;
  7892. return path.substring(index + 1);
  7893. };
  7894. /**
  7895. * Extracts the "folder" part of a path (everything before the filename).
  7896. * @param uri The URI to extract the info from
  7897. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7898. * @returns The "folder" part of the path
  7899. */
  7900. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7901. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7902. var index = uri.lastIndexOf("/");
  7903. if (index < 0) {
  7904. if (returnUnchangedIfNoSlash) {
  7905. return uri;
  7906. }
  7907. return "";
  7908. }
  7909. return uri.substring(0, index + 1);
  7910. };
  7911. Tools.GetDOMTextContent = function (element) {
  7912. var result = "";
  7913. var child = element.firstChild;
  7914. while (child) {
  7915. if (child.nodeType === 3) {
  7916. result += child.textContent;
  7917. }
  7918. child = child.nextSibling;
  7919. }
  7920. return result;
  7921. };
  7922. Tools.ToDegrees = function (angle) {
  7923. return angle * 180 / Math.PI;
  7924. };
  7925. Tools.ToRadians = function (angle) {
  7926. return angle * Math.PI / 180;
  7927. };
  7928. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7929. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7930. var output = "";
  7931. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7932. var i = 0;
  7933. var bytes = new Uint8Array(buffer);
  7934. while (i < bytes.length) {
  7935. chr1 = bytes[i++];
  7936. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7937. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7938. enc1 = chr1 >> 2;
  7939. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7940. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7941. enc4 = chr3 & 63;
  7942. if (isNaN(chr2)) {
  7943. enc3 = enc4 = 64;
  7944. }
  7945. else if (isNaN(chr3)) {
  7946. enc4 = 64;
  7947. }
  7948. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7949. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7950. }
  7951. return "data:image/png;base64," + output;
  7952. };
  7953. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7954. if (bias === void 0) { bias = null; }
  7955. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7956. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7957. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7958. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7959. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7960. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7961. }
  7962. if (bias) {
  7963. minimum.x -= minimum.x * bias.x + bias.y;
  7964. minimum.y -= minimum.y * bias.x + bias.y;
  7965. minimum.z -= minimum.z * bias.x + bias.y;
  7966. maximum.x += maximum.x * bias.x + bias.y;
  7967. maximum.y += maximum.y * bias.x + bias.y;
  7968. maximum.z += maximum.z * bias.x + bias.y;
  7969. }
  7970. return {
  7971. minimum: minimum,
  7972. maximum: maximum
  7973. };
  7974. };
  7975. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7976. if (bias === void 0) { bias = null; }
  7977. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7978. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7979. if (!stride) {
  7980. stride = 3;
  7981. }
  7982. for (var index = start; index < start + count; index++) {
  7983. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7984. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7985. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7986. }
  7987. if (bias) {
  7988. minimum.x -= minimum.x * bias.x + bias.y;
  7989. minimum.y -= minimum.y * bias.x + bias.y;
  7990. minimum.z -= minimum.z * bias.x + bias.y;
  7991. maximum.x += maximum.x * bias.x + bias.y;
  7992. maximum.y += maximum.y * bias.x + bias.y;
  7993. maximum.z += maximum.z * bias.x + bias.y;
  7994. }
  7995. return {
  7996. minimum: minimum,
  7997. maximum: maximum
  7998. };
  7999. };
  8000. Tools.Vector2ArrayFeeder = function (array) {
  8001. return function (index) {
  8002. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8003. var length = isFloatArray ? array.length / 2 : array.length;
  8004. if (index >= length) {
  8005. return null;
  8006. }
  8007. if (isFloatArray) {
  8008. var fa = array;
  8009. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8010. }
  8011. var a = array;
  8012. return a[index];
  8013. };
  8014. };
  8015. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8016. if (bias === void 0) { bias = null; }
  8017. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8018. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8019. var i = 0;
  8020. var cur = feeder(i++);
  8021. while (cur) {
  8022. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8023. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8024. cur = feeder(i++);
  8025. }
  8026. if (bias) {
  8027. minimum.x -= minimum.x * bias.x + bias.y;
  8028. minimum.y -= minimum.y * bias.x + bias.y;
  8029. maximum.x += maximum.x * bias.x + bias.y;
  8030. maximum.y += maximum.y * bias.x + bias.y;
  8031. }
  8032. return {
  8033. minimum: minimum,
  8034. maximum: maximum
  8035. };
  8036. };
  8037. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8038. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8039. return null;
  8040. return Array.isArray(obj) ? obj : [obj];
  8041. };
  8042. // Misc.
  8043. Tools.GetPointerPrefix = function () {
  8044. var eventPrefix = "pointer";
  8045. // Check if pointer events are supported
  8046. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8047. eventPrefix = "mouse";
  8048. }
  8049. return eventPrefix;
  8050. };
  8051. /**
  8052. * @param func - the function to be called
  8053. * @param requester - the object that will request the next frame. Falls back to window.
  8054. */
  8055. Tools.QueueNewFrame = function (func, requester) {
  8056. if (!Tools.IsWindowObjectExist()) {
  8057. return setTimeout(func, 16);
  8058. }
  8059. if (!requester) {
  8060. requester = window;
  8061. }
  8062. if (requester.requestAnimationFrame) {
  8063. return requester.requestAnimationFrame(func);
  8064. }
  8065. else if (requester.msRequestAnimationFrame) {
  8066. return requester.msRequestAnimationFrame(func);
  8067. }
  8068. else if (requester.webkitRequestAnimationFrame) {
  8069. return requester.webkitRequestAnimationFrame(func);
  8070. }
  8071. else if (requester.mozRequestAnimationFrame) {
  8072. return requester.mozRequestAnimationFrame(func);
  8073. }
  8074. else if (requester.oRequestAnimationFrame) {
  8075. return requester.oRequestAnimationFrame(func);
  8076. }
  8077. else {
  8078. return window.setTimeout(func, 16);
  8079. }
  8080. };
  8081. Tools.RequestFullscreen = function (element) {
  8082. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8083. if (!requestFunction)
  8084. return;
  8085. requestFunction.call(element);
  8086. };
  8087. Tools.ExitFullscreen = function () {
  8088. if (document.exitFullscreen) {
  8089. document.exitFullscreen();
  8090. }
  8091. else if (document.mozCancelFullScreen) {
  8092. document.mozCancelFullScreen();
  8093. }
  8094. else if (document.webkitCancelFullScreen) {
  8095. document.webkitCancelFullScreen();
  8096. }
  8097. else if (document.msCancelFullScreen) {
  8098. document.msCancelFullScreen();
  8099. }
  8100. };
  8101. Tools.SetCorsBehavior = function (url, element) {
  8102. if (url && url.indexOf("data:") === 0) {
  8103. return;
  8104. }
  8105. if (Tools.CorsBehavior) {
  8106. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8107. element.crossOrigin = Tools.CorsBehavior;
  8108. }
  8109. else {
  8110. var result = Tools.CorsBehavior(url);
  8111. if (result) {
  8112. element.crossOrigin = result;
  8113. }
  8114. }
  8115. }
  8116. };
  8117. // External files
  8118. Tools.CleanUrl = function (url) {
  8119. url = url.replace(/#/mg, "%23");
  8120. return url;
  8121. };
  8122. Tools.LoadImage = function (url, onLoad, onError, database) {
  8123. if (url instanceof ArrayBuffer) {
  8124. url = Tools.EncodeArrayBufferTobase64(url);
  8125. }
  8126. url = Tools.CleanUrl(url);
  8127. url = Tools.PreprocessUrl(url);
  8128. var img = new Image();
  8129. Tools.SetCorsBehavior(url, img);
  8130. var loadHandler = function () {
  8131. img.removeEventListener("load", loadHandler);
  8132. img.removeEventListener("error", errorHandler);
  8133. onLoad(img);
  8134. };
  8135. var errorHandler = function (err) {
  8136. img.removeEventListener("load", loadHandler);
  8137. img.removeEventListener("error", errorHandler);
  8138. Tools.Error("Error while trying to load image: " + url);
  8139. if (onError) {
  8140. onError("Error while trying to load image: " + url, err);
  8141. }
  8142. };
  8143. img.addEventListener("load", loadHandler);
  8144. img.addEventListener("error", errorHandler);
  8145. var noIndexedDB = function () {
  8146. img.src = url;
  8147. };
  8148. var loadFromIndexedDB = function () {
  8149. if (database) {
  8150. database.loadImageFromDB(url, img);
  8151. }
  8152. };
  8153. //ANY database to do!
  8154. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8155. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8156. }
  8157. else {
  8158. if (url.indexOf("file:") !== -1) {
  8159. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8160. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8161. try {
  8162. var blobURL;
  8163. try {
  8164. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8165. }
  8166. catch (ex) {
  8167. // Chrome doesn't support oneTimeOnly parameter
  8168. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8169. }
  8170. img.src = blobURL;
  8171. }
  8172. catch (e) {
  8173. img.src = "";
  8174. }
  8175. return img;
  8176. }
  8177. }
  8178. noIndexedDB();
  8179. }
  8180. return img;
  8181. };
  8182. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8183. url = Tools.CleanUrl(url);
  8184. url = Tools.PreprocessUrl(url);
  8185. // If file and file input are set
  8186. if (url.indexOf("file:") !== -1) {
  8187. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8188. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8189. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8190. }
  8191. }
  8192. var loadUrl = Tools.BaseUrl + url;
  8193. var aborted = false;
  8194. var fileRequest = {
  8195. onCompleteObservable: new BABYLON.Observable(),
  8196. abort: function () { return aborted = true; },
  8197. };
  8198. var requestFile = function () {
  8199. var request = new XMLHttpRequest();
  8200. var retryHandle = null;
  8201. fileRequest.abort = function () {
  8202. aborted = true;
  8203. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8204. request.abort();
  8205. }
  8206. if (retryHandle !== null) {
  8207. clearTimeout(retryHandle);
  8208. retryHandle = null;
  8209. }
  8210. };
  8211. var retryLoop = function (retryIndex) {
  8212. request.open('GET', loadUrl, true);
  8213. if (useArrayBuffer) {
  8214. request.responseType = "arraybuffer";
  8215. }
  8216. if (onProgress) {
  8217. request.addEventListener("progress", onProgress);
  8218. }
  8219. var onLoadEnd = function () {
  8220. request.removeEventListener("loadend", onLoadEnd);
  8221. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8222. fileRequest.onCompleteObservable.clear();
  8223. };
  8224. request.addEventListener("loadend", onLoadEnd);
  8225. var onReadyStateChange = function () {
  8226. if (aborted) {
  8227. return;
  8228. }
  8229. // In case of undefined state in some browsers.
  8230. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8231. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8232. request.removeEventListener("readystatechange", onReadyStateChange);
  8233. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8234. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8235. return;
  8236. }
  8237. var retryStrategy = Tools.DefaultRetryStrategy;
  8238. if (retryStrategy) {
  8239. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8240. if (waitTime !== -1) {
  8241. // Prevent the request from completing for retry.
  8242. request.removeEventListener("loadend", onLoadEnd);
  8243. request = new XMLHttpRequest();
  8244. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8245. return;
  8246. }
  8247. }
  8248. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8249. if (onError) {
  8250. onError(request, e);
  8251. }
  8252. else {
  8253. throw e;
  8254. }
  8255. }
  8256. };
  8257. request.addEventListener("readystatechange", onReadyStateChange);
  8258. request.send();
  8259. };
  8260. retryLoop(0);
  8261. };
  8262. // Caching all files
  8263. if (database && database.enableSceneOffline) {
  8264. var noIndexedDB_1 = function () {
  8265. if (!aborted) {
  8266. requestFile();
  8267. }
  8268. };
  8269. var loadFromIndexedDB = function () {
  8270. // TODO: database needs to support aborting and should return a IFileRequest
  8271. if (aborted) {
  8272. return;
  8273. }
  8274. if (database) {
  8275. database.loadFileFromDB(url, function (data) {
  8276. if (!aborted) {
  8277. onSuccess(data);
  8278. }
  8279. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8280. }, onProgress ? function (event) {
  8281. if (!aborted) {
  8282. onProgress(event);
  8283. }
  8284. } : undefined, noIndexedDB_1, useArrayBuffer);
  8285. }
  8286. };
  8287. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8288. }
  8289. else {
  8290. requestFile();
  8291. }
  8292. return fileRequest;
  8293. };
  8294. /**
  8295. * Load a script (identified by an url). When the url returns, the
  8296. * content of this file is added into a new script element, attached to the DOM (body element)
  8297. */
  8298. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8299. var head = document.getElementsByTagName('head')[0];
  8300. var script = document.createElement('script');
  8301. script.type = 'text/javascript';
  8302. script.src = scriptUrl;
  8303. script.onload = function () {
  8304. if (onSuccess) {
  8305. onSuccess();
  8306. }
  8307. };
  8308. script.onerror = function (e) {
  8309. if (onError) {
  8310. onError("Unable to load script", e);
  8311. }
  8312. };
  8313. head.appendChild(script);
  8314. };
  8315. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8316. var reader = new FileReader();
  8317. var request = {
  8318. onCompleteObservable: new BABYLON.Observable(),
  8319. abort: function () { return reader.abort(); },
  8320. };
  8321. reader.onloadend = function (e) {
  8322. request.onCompleteObservable.notifyObservers(request);
  8323. };
  8324. reader.onload = function (e) {
  8325. //target doesn't have result from ts 1.3
  8326. callback(e.target['result']);
  8327. };
  8328. reader.onprogress = progressCallback;
  8329. reader.readAsDataURL(fileToLoad);
  8330. return request;
  8331. };
  8332. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8333. var reader = new FileReader();
  8334. var request = {
  8335. onCompleteObservable: new BABYLON.Observable(),
  8336. abort: function () { return reader.abort(); },
  8337. };
  8338. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8339. reader.onerror = function (e) {
  8340. Tools.Log("Error while reading file: " + fileToLoad.name);
  8341. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8342. };
  8343. reader.onload = function (e) {
  8344. //target doesn't have result from ts 1.3
  8345. callback(e.target['result']);
  8346. };
  8347. if (progressCallBack) {
  8348. reader.onprogress = progressCallBack;
  8349. }
  8350. if (!useArrayBuffer) {
  8351. // Asynchronous read
  8352. reader.readAsText(fileToLoad);
  8353. }
  8354. else {
  8355. reader.readAsArrayBuffer(fileToLoad);
  8356. }
  8357. return request;
  8358. };
  8359. //returns a downloadable url to a file content.
  8360. Tools.FileAsURL = function (content) {
  8361. var fileBlob = new Blob([content]);
  8362. var url = window.URL || window.webkitURL;
  8363. var link = url.createObjectURL(fileBlob);
  8364. return link;
  8365. };
  8366. // Misc.
  8367. Tools.Format = function (value, decimals) {
  8368. if (decimals === void 0) { decimals = 2; }
  8369. return value.toFixed(decimals);
  8370. };
  8371. Tools.CheckExtends = function (v, min, max) {
  8372. if (v.x < min.x)
  8373. min.x = v.x;
  8374. if (v.y < min.y)
  8375. min.y = v.y;
  8376. if (v.z < min.z)
  8377. min.z = v.z;
  8378. if (v.x > max.x)
  8379. max.x = v.x;
  8380. if (v.y > max.y)
  8381. max.y = v.y;
  8382. if (v.z > max.z)
  8383. max.z = v.z;
  8384. };
  8385. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8386. for (var prop in source) {
  8387. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8388. continue;
  8389. }
  8390. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8391. continue;
  8392. }
  8393. var sourceValue = source[prop];
  8394. var typeOfSourceValue = typeof sourceValue;
  8395. if (typeOfSourceValue === "function") {
  8396. continue;
  8397. }
  8398. if (typeOfSourceValue === "object") {
  8399. if (sourceValue instanceof Array) {
  8400. destination[prop] = [];
  8401. if (sourceValue.length > 0) {
  8402. if (typeof sourceValue[0] == "object") {
  8403. for (var index = 0; index < sourceValue.length; index++) {
  8404. var clonedValue = cloneValue(sourceValue[index], destination);
  8405. if (destination[prop].indexOf(clonedValue) === -1) {
  8406. destination[prop].push(clonedValue);
  8407. }
  8408. }
  8409. }
  8410. else {
  8411. destination[prop] = sourceValue.slice(0);
  8412. }
  8413. }
  8414. }
  8415. else {
  8416. destination[prop] = cloneValue(sourceValue, destination);
  8417. }
  8418. }
  8419. else {
  8420. destination[prop] = sourceValue;
  8421. }
  8422. }
  8423. };
  8424. Tools.IsEmpty = function (obj) {
  8425. for (var i in obj) {
  8426. if (obj.hasOwnProperty(i)) {
  8427. return false;
  8428. }
  8429. }
  8430. return true;
  8431. };
  8432. Tools.RegisterTopRootEvents = function (events) {
  8433. for (var index = 0; index < events.length; index++) {
  8434. var event = events[index];
  8435. window.addEventListener(event.name, event.handler, false);
  8436. try {
  8437. if (window.parent) {
  8438. window.parent.addEventListener(event.name, event.handler, false);
  8439. }
  8440. }
  8441. catch (e) {
  8442. // Silently fails...
  8443. }
  8444. }
  8445. };
  8446. Tools.UnregisterTopRootEvents = function (events) {
  8447. for (var index = 0; index < events.length; index++) {
  8448. var event = events[index];
  8449. window.removeEventListener(event.name, event.handler);
  8450. try {
  8451. if (window.parent) {
  8452. window.parent.removeEventListener(event.name, event.handler);
  8453. }
  8454. }
  8455. catch (e) {
  8456. // Silently fails...
  8457. }
  8458. }
  8459. };
  8460. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8461. if (mimeType === void 0) { mimeType = "image/png"; }
  8462. // Read the contents of the framebuffer
  8463. var numberOfChannelsByLine = width * 4;
  8464. var halfHeight = height / 2;
  8465. //Reading datas from WebGL
  8466. var data = engine.readPixels(0, 0, width, height);
  8467. //To flip image on Y axis.
  8468. for (var i = 0; i < halfHeight; i++) {
  8469. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8470. var currentCell = j + i * numberOfChannelsByLine;
  8471. var targetLine = height - i - 1;
  8472. var targetCell = j + targetLine * numberOfChannelsByLine;
  8473. var temp = data[currentCell];
  8474. data[currentCell] = data[targetCell];
  8475. data[targetCell] = temp;
  8476. }
  8477. }
  8478. // Create a 2D canvas to store the result
  8479. if (!screenshotCanvas) {
  8480. screenshotCanvas = document.createElement('canvas');
  8481. }
  8482. screenshotCanvas.width = width;
  8483. screenshotCanvas.height = height;
  8484. var context = screenshotCanvas.getContext('2d');
  8485. if (context) {
  8486. // Copy the pixels to a 2D canvas
  8487. var imageData = context.createImageData(width, height);
  8488. var castData = (imageData.data);
  8489. castData.set(data);
  8490. context.putImageData(imageData, 0, 0);
  8491. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8492. }
  8493. };
  8494. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8495. if (mimeType === void 0) { mimeType = "image/png"; }
  8496. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8497. if (successCallback) {
  8498. successCallback(base64Image);
  8499. }
  8500. else {
  8501. // We need HTMLCanvasElement.toBlob for HD screenshots
  8502. if (!screenshotCanvas.toBlob) {
  8503. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8504. screenshotCanvas.toBlob = function (callback, type, quality) {
  8505. var _this = this;
  8506. setTimeout(function () {
  8507. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8508. for (var i = 0; i < len; i++) {
  8509. arr[i] = binStr.charCodeAt(i);
  8510. }
  8511. callback(new Blob([arr], { type: type || 'image/png' }));
  8512. });
  8513. };
  8514. }
  8515. screenshotCanvas.toBlob(function (blob) {
  8516. var url = URL.createObjectURL(blob);
  8517. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8518. if (("download" in document.createElement("a"))) {
  8519. var a = window.document.createElement("a");
  8520. a.href = url;
  8521. if (fileName) {
  8522. a.setAttribute("download", fileName);
  8523. }
  8524. else {
  8525. var date = new Date();
  8526. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8527. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8528. }
  8529. window.document.body.appendChild(a);
  8530. a.addEventListener("click", function () {
  8531. if (a.parentElement) {
  8532. a.parentElement.removeChild(a);
  8533. }
  8534. });
  8535. a.click();
  8536. }
  8537. else {
  8538. var newWindow = window.open("");
  8539. if (!newWindow)
  8540. return;
  8541. var img = newWindow.document.createElement("img");
  8542. img.onload = function () {
  8543. // no longer need to read the blob so it's revoked
  8544. URL.revokeObjectURL(url);
  8545. };
  8546. img.src = url;
  8547. newWindow.document.body.appendChild(img);
  8548. }
  8549. });
  8550. }
  8551. };
  8552. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8553. if (mimeType === void 0) { mimeType = "image/png"; }
  8554. var width;
  8555. var height;
  8556. // If a precision value is specified
  8557. if (size.precision) {
  8558. width = Math.round(engine.getRenderWidth() * size.precision);
  8559. height = Math.round(width / engine.getAspectRatio(camera));
  8560. }
  8561. else if (size.width && size.height) {
  8562. width = size.width;
  8563. height = size.height;
  8564. }
  8565. else if (size.width && !size.height) {
  8566. width = size.width;
  8567. height = Math.round(width / engine.getAspectRatio(camera));
  8568. }
  8569. else if (size.height && !size.width) {
  8570. height = size.height;
  8571. width = Math.round(height * engine.getAspectRatio(camera));
  8572. }
  8573. else if (!isNaN(size)) {
  8574. height = size;
  8575. width = size;
  8576. }
  8577. else {
  8578. Tools.Error("Invalid 'size' parameter !");
  8579. return;
  8580. }
  8581. if (!screenshotCanvas) {
  8582. screenshotCanvas = document.createElement('canvas');
  8583. }
  8584. screenshotCanvas.width = width;
  8585. screenshotCanvas.height = height;
  8586. var renderContext = screenshotCanvas.getContext("2d");
  8587. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8588. var newWidth = width;
  8589. var newHeight = newWidth / ratio;
  8590. if (newHeight > height) {
  8591. newHeight = height;
  8592. newWidth = newHeight * ratio;
  8593. }
  8594. var offsetX = Math.max(0, width - newWidth) / 2;
  8595. var offsetY = Math.max(0, height - newHeight) / 2;
  8596. var renderingCanvas = engine.getRenderingCanvas();
  8597. if (renderContext && renderingCanvas) {
  8598. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8599. }
  8600. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8601. };
  8602. /**
  8603. * Generates an image screenshot from the specified camera.
  8604. *
  8605. * @param engine The engine to use for rendering
  8606. * @param camera The camera to use for rendering
  8607. * @param size This parameter can be set to a single number or to an object with the
  8608. * following (optional) properties: precision, width, height. If a single number is passed,
  8609. * it will be used for both width and height. If an object is passed, the screenshot size
  8610. * will be derived from the parameters. The precision property is a multiplier allowing
  8611. * rendering at a higher or lower resolution.
  8612. * @param successCallback The callback receives a single parameter which contains the
  8613. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8614. * src parameter of an <img> to display it.
  8615. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8616. * Check your browser for supported MIME types.
  8617. * @param samples Texture samples (default: 1)
  8618. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8619. * @param fileName A name for for the downloaded file.
  8620. * @constructor
  8621. */
  8622. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8623. if (mimeType === void 0) { mimeType = "image/png"; }
  8624. if (samples === void 0) { samples = 1; }
  8625. if (antialiasing === void 0) { antialiasing = false; }
  8626. var width;
  8627. var height;
  8628. //If a precision value is specified
  8629. if (size.precision) {
  8630. width = Math.round(engine.getRenderWidth() * size.precision);
  8631. height = Math.round(width / engine.getAspectRatio(camera));
  8632. size = { width: width, height: height };
  8633. }
  8634. else if (size.width && size.height) {
  8635. width = size.width;
  8636. height = size.height;
  8637. }
  8638. else if (size.width && !size.height) {
  8639. width = size.width;
  8640. height = Math.round(width / engine.getAspectRatio(camera));
  8641. size = { width: width, height: height };
  8642. }
  8643. else if (size.height && !size.width) {
  8644. height = size.height;
  8645. width = Math.round(height * engine.getAspectRatio(camera));
  8646. size = { width: width, height: height };
  8647. }
  8648. else if (!isNaN(size)) {
  8649. height = size;
  8650. width = size;
  8651. }
  8652. else {
  8653. Tools.Error("Invalid 'size' parameter !");
  8654. return;
  8655. }
  8656. var scene = camera.getScene();
  8657. var previousCamera = null;
  8658. if (scene.activeCamera !== camera) {
  8659. previousCamera = scene.activeCamera;
  8660. scene.activeCamera = camera;
  8661. }
  8662. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8663. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8664. texture.renderList = null;
  8665. texture.samples = samples;
  8666. if (antialiasing) {
  8667. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8668. }
  8669. texture.onAfterRenderObservable.add(function () {
  8670. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8671. });
  8672. scene.incrementRenderId();
  8673. scene.resetCachedMaterial();
  8674. texture.render(true);
  8675. texture.dispose();
  8676. if (previousCamera) {
  8677. scene.activeCamera = previousCamera;
  8678. }
  8679. camera.getProjectionMatrix(true); // Force cache refresh;
  8680. };
  8681. // XHR response validator for local file scenario
  8682. Tools.ValidateXHRData = function (xhr, dataType) {
  8683. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8684. if (dataType === void 0) { dataType = 7; }
  8685. try {
  8686. if (dataType & 1) {
  8687. if (xhr.responseText && xhr.responseText.length > 0) {
  8688. return true;
  8689. }
  8690. else if (dataType === 1) {
  8691. return false;
  8692. }
  8693. }
  8694. if (dataType & 2) {
  8695. // Check header width and height since there is no "TGA" magic number
  8696. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8697. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8698. return true;
  8699. }
  8700. else if (dataType === 2) {
  8701. return false;
  8702. }
  8703. }
  8704. if (dataType & 4) {
  8705. // Check for the "DDS" magic number
  8706. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8707. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8708. return true;
  8709. }
  8710. else {
  8711. return false;
  8712. }
  8713. }
  8714. }
  8715. catch (e) {
  8716. // Global protection
  8717. }
  8718. return false;
  8719. };
  8720. /**
  8721. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8722. * Be aware Math.random() could cause collisions, but:
  8723. * "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"
  8724. */
  8725. Tools.RandomId = function () {
  8726. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8727. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8728. return v.toString(16);
  8729. });
  8730. };
  8731. /**
  8732. * Test if the given uri is a base64 string.
  8733. * @param uri The uri to test
  8734. * @return True if the uri is a base64 string or false otherwise.
  8735. */
  8736. Tools.IsBase64 = function (uri) {
  8737. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8738. };
  8739. /**
  8740. * Decode the given base64 uri.
  8741. * @param uri The uri to decode
  8742. * @return The decoded base64 data.
  8743. */
  8744. Tools.DecodeBase64 = function (uri) {
  8745. var decodedString = atob(uri.split(",")[1]);
  8746. var bufferLength = decodedString.length;
  8747. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8748. for (var i = 0; i < bufferLength; i++) {
  8749. bufferView[i] = decodedString.charCodeAt(i);
  8750. }
  8751. return bufferView.buffer;
  8752. };
  8753. Object.defineProperty(Tools, "NoneLogLevel", {
  8754. get: function () {
  8755. return Tools._NoneLogLevel;
  8756. },
  8757. enumerable: true,
  8758. configurable: true
  8759. });
  8760. Object.defineProperty(Tools, "MessageLogLevel", {
  8761. get: function () {
  8762. return Tools._MessageLogLevel;
  8763. },
  8764. enumerable: true,
  8765. configurable: true
  8766. });
  8767. Object.defineProperty(Tools, "WarningLogLevel", {
  8768. get: function () {
  8769. return Tools._WarningLogLevel;
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. Object.defineProperty(Tools, "ErrorLogLevel", {
  8775. get: function () {
  8776. return Tools._ErrorLogLevel;
  8777. },
  8778. enumerable: true,
  8779. configurable: true
  8780. });
  8781. Object.defineProperty(Tools, "AllLogLevel", {
  8782. get: function () {
  8783. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8784. },
  8785. enumerable: true,
  8786. configurable: true
  8787. });
  8788. Tools._AddLogEntry = function (entry) {
  8789. Tools._LogCache = entry + Tools._LogCache;
  8790. if (Tools.OnNewCacheEntry) {
  8791. Tools.OnNewCacheEntry(entry);
  8792. }
  8793. };
  8794. Tools._FormatMessage = function (message) {
  8795. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8796. var date = new Date();
  8797. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8798. };
  8799. Tools._LogDisabled = function (message) {
  8800. // nothing to do
  8801. };
  8802. Tools._LogEnabled = function (message) {
  8803. var formattedMessage = Tools._FormatMessage(message);
  8804. console.log("BJS - " + formattedMessage);
  8805. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8806. Tools._AddLogEntry(entry);
  8807. };
  8808. Tools._WarnDisabled = function (message) {
  8809. // nothing to do
  8810. };
  8811. Tools._WarnEnabled = function (message) {
  8812. var formattedMessage = Tools._FormatMessage(message);
  8813. console.warn("BJS - " + formattedMessage);
  8814. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8815. Tools._AddLogEntry(entry);
  8816. };
  8817. Tools._ErrorDisabled = function (message) {
  8818. // nothing to do
  8819. };
  8820. Tools._ErrorEnabled = function (message) {
  8821. Tools.errorsCount++;
  8822. var formattedMessage = Tools._FormatMessage(message);
  8823. console.error("BJS - " + formattedMessage);
  8824. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8825. Tools._AddLogEntry(entry);
  8826. };
  8827. Object.defineProperty(Tools, "LogCache", {
  8828. get: function () {
  8829. return Tools._LogCache;
  8830. },
  8831. enumerable: true,
  8832. configurable: true
  8833. });
  8834. Tools.ClearLogCache = function () {
  8835. Tools._LogCache = "";
  8836. Tools.errorsCount = 0;
  8837. };
  8838. Object.defineProperty(Tools, "LogLevels", {
  8839. set: function (level) {
  8840. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8841. Tools.Log = Tools._LogEnabled;
  8842. }
  8843. else {
  8844. Tools.Log = Tools._LogDisabled;
  8845. }
  8846. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8847. Tools.Warn = Tools._WarnEnabled;
  8848. }
  8849. else {
  8850. Tools.Warn = Tools._WarnDisabled;
  8851. }
  8852. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8853. Tools.Error = Tools._ErrorEnabled;
  8854. }
  8855. else {
  8856. Tools.Error = Tools._ErrorDisabled;
  8857. }
  8858. },
  8859. enumerable: true,
  8860. configurable: true
  8861. });
  8862. Tools.IsWindowObjectExist = function () {
  8863. return (typeof window) !== "undefined";
  8864. };
  8865. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8866. get: function () {
  8867. return Tools._PerformanceNoneLogLevel;
  8868. },
  8869. enumerable: true,
  8870. configurable: true
  8871. });
  8872. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8873. get: function () {
  8874. return Tools._PerformanceUserMarkLogLevel;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8880. get: function () {
  8881. return Tools._PerformanceConsoleLogLevel;
  8882. },
  8883. enumerable: true,
  8884. configurable: true
  8885. });
  8886. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8887. set: function (level) {
  8888. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8889. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8890. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8891. return;
  8892. }
  8893. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8894. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8895. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8896. return;
  8897. }
  8898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8900. },
  8901. enumerable: true,
  8902. configurable: true
  8903. });
  8904. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8905. };
  8906. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8907. };
  8908. Tools._StartUserMark = function (counterName, condition) {
  8909. if (condition === void 0) { condition = true; }
  8910. if (!Tools._performance) {
  8911. if (!Tools.IsWindowObjectExist()) {
  8912. return;
  8913. }
  8914. Tools._performance = window.performance;
  8915. }
  8916. if (!condition || !Tools._performance.mark) {
  8917. return;
  8918. }
  8919. Tools._performance.mark(counterName + "-Begin");
  8920. };
  8921. Tools._EndUserMark = function (counterName, condition) {
  8922. if (condition === void 0) { condition = true; }
  8923. if (!condition || !Tools._performance.mark) {
  8924. return;
  8925. }
  8926. Tools._performance.mark(counterName + "-End");
  8927. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8928. };
  8929. Tools._StartPerformanceConsole = function (counterName, condition) {
  8930. if (condition === void 0) { condition = true; }
  8931. if (!condition) {
  8932. return;
  8933. }
  8934. Tools._StartUserMark(counterName, condition);
  8935. if (console.time) {
  8936. console.time(counterName);
  8937. }
  8938. };
  8939. Tools._EndPerformanceConsole = function (counterName, condition) {
  8940. if (condition === void 0) { condition = true; }
  8941. if (!condition) {
  8942. return;
  8943. }
  8944. Tools._EndUserMark(counterName, condition);
  8945. if (console.time) {
  8946. console.timeEnd(counterName);
  8947. }
  8948. };
  8949. Object.defineProperty(Tools, "Now", {
  8950. get: function () {
  8951. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8952. return window.performance.now();
  8953. }
  8954. return new Date().getTime();
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. /**
  8960. * This method will return the name of the class used to create the instance of the given object.
  8961. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8962. * @param object the object to get the class name from
  8963. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8964. */
  8965. Tools.GetClassName = function (object, isType) {
  8966. if (isType === void 0) { isType = false; }
  8967. var name = null;
  8968. if (!isType && object.getClassName) {
  8969. name = object.getClassName();
  8970. }
  8971. else {
  8972. if (object instanceof Object) {
  8973. var classObj = isType ? object : Object.getPrototypeOf(object);
  8974. name = classObj.constructor["__bjsclassName__"];
  8975. }
  8976. if (!name) {
  8977. name = typeof object;
  8978. }
  8979. }
  8980. return name;
  8981. };
  8982. Tools.First = function (array, predicate) {
  8983. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8984. var el = array_1[_i];
  8985. if (predicate(el)) {
  8986. return el;
  8987. }
  8988. }
  8989. return null;
  8990. };
  8991. /**
  8992. * This method will return the name of the full name of the class, including its owning module (if any).
  8993. * 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).
  8994. * @param object the object to get the class name from
  8995. * @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.
  8996. */
  8997. Tools.getFullClassName = function (object, isType) {
  8998. if (isType === void 0) { isType = false; }
  8999. var className = null;
  9000. var moduleName = null;
  9001. if (!isType && object.getClassName) {
  9002. className = object.getClassName();
  9003. }
  9004. else {
  9005. if (object instanceof Object) {
  9006. var classObj = isType ? object : Object.getPrototypeOf(object);
  9007. className = classObj.constructor["__bjsclassName__"];
  9008. moduleName = classObj.constructor["__bjsmoduleName__"];
  9009. }
  9010. if (!className) {
  9011. className = typeof object;
  9012. }
  9013. }
  9014. if (!className) {
  9015. return null;
  9016. }
  9017. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9018. };
  9019. /**
  9020. * 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.
  9021. * @param array
  9022. */
  9023. Tools.arrayOrStringFeeder = function (array) {
  9024. return function (index) {
  9025. if (index >= array.length) {
  9026. return null;
  9027. }
  9028. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9029. if (val && val.getHashCode) {
  9030. val = val.getHashCode();
  9031. }
  9032. if (typeof val === "string") {
  9033. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9034. }
  9035. return val;
  9036. };
  9037. };
  9038. /**
  9039. * Compute the hashCode of a stream of number
  9040. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9041. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9042. * @return the hash code computed
  9043. */
  9044. Tools.hashCodeFromStream = function (feeder) {
  9045. // Based from here: http://stackoverflow.com/a/7616484/802124
  9046. var hash = 0;
  9047. var index = 0;
  9048. var chr = feeder(index++);
  9049. while (chr != null) {
  9050. hash = ((hash << 5) - hash) + chr;
  9051. hash |= 0; // Convert to 32bit integer
  9052. chr = feeder(index++);
  9053. }
  9054. return hash;
  9055. };
  9056. /**
  9057. * Returns a promise that resolves after the given amount of time.
  9058. * @param delay Number of milliseconds to delay
  9059. * @returns Promise that resolves after the given amount of time
  9060. */
  9061. Tools.DelayAsync = function (delay) {
  9062. return new Promise(function (resolve) {
  9063. setTimeout(function () {
  9064. resolve();
  9065. }, delay);
  9066. });
  9067. };
  9068. Tools.BaseUrl = "";
  9069. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9070. /**
  9071. * Default behaviour for cors in the application.
  9072. * It can be a string if the expected behavior is identical in the entire app.
  9073. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9074. */
  9075. Tools.CorsBehavior = "anonymous";
  9076. Tools.UseFallbackTexture = true;
  9077. /**
  9078. * Use this object to register external classes like custom textures or material
  9079. * to allow the laoders to instantiate them
  9080. */
  9081. Tools.RegisteredExternalClasses = {};
  9082. // Used in case of a texture loading problem
  9083. 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";
  9084. Tools.PreprocessUrl = function (url) {
  9085. return url;
  9086. };
  9087. // Logs
  9088. Tools._NoneLogLevel = 0;
  9089. Tools._MessageLogLevel = 1;
  9090. Tools._WarningLogLevel = 2;
  9091. Tools._ErrorLogLevel = 4;
  9092. Tools._LogCache = "";
  9093. Tools.errorsCount = 0;
  9094. Tools.Log = Tools._LogEnabled;
  9095. Tools.Warn = Tools._WarnEnabled;
  9096. Tools.Error = Tools._ErrorEnabled;
  9097. // Performances
  9098. Tools._PerformanceNoneLogLevel = 0;
  9099. Tools._PerformanceUserMarkLogLevel = 1;
  9100. Tools._PerformanceConsoleLogLevel = 2;
  9101. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9102. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9103. return Tools;
  9104. }());
  9105. BABYLON.Tools = Tools;
  9106. /**
  9107. * This class is used to track a performance counter which is number based.
  9108. * The user has access to many properties which give statistics of different nature
  9109. *
  9110. * The implementer can track two kinds of Performance Counter: time and count
  9111. * 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.
  9112. * 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.
  9113. */
  9114. var PerfCounter = /** @class */ (function () {
  9115. function PerfCounter() {
  9116. this._startMonitoringTime = 0;
  9117. this._min = 0;
  9118. this._max = 0;
  9119. this._average = 0;
  9120. this._lastSecAverage = 0;
  9121. this._current = 0;
  9122. this._totalValueCount = 0;
  9123. this._totalAccumulated = 0;
  9124. this._lastSecAccumulated = 0;
  9125. this._lastSecTime = 0;
  9126. this._lastSecValueCount = 0;
  9127. }
  9128. Object.defineProperty(PerfCounter.prototype, "min", {
  9129. /**
  9130. * Returns the smallest value ever
  9131. */
  9132. get: function () {
  9133. return this._min;
  9134. },
  9135. enumerable: true,
  9136. configurable: true
  9137. });
  9138. Object.defineProperty(PerfCounter.prototype, "max", {
  9139. /**
  9140. * Returns the biggest value ever
  9141. */
  9142. get: function () {
  9143. return this._max;
  9144. },
  9145. enumerable: true,
  9146. configurable: true
  9147. });
  9148. Object.defineProperty(PerfCounter.prototype, "average", {
  9149. /**
  9150. * Returns the average value since the performance counter is running
  9151. */
  9152. get: function () {
  9153. return this._average;
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9159. /**
  9160. * Returns the average value of the last second the counter was monitored
  9161. */
  9162. get: function () {
  9163. return this._lastSecAverage;
  9164. },
  9165. enumerable: true,
  9166. configurable: true
  9167. });
  9168. Object.defineProperty(PerfCounter.prototype, "current", {
  9169. /**
  9170. * Returns the current value
  9171. */
  9172. get: function () {
  9173. return this._current;
  9174. },
  9175. enumerable: true,
  9176. configurable: true
  9177. });
  9178. Object.defineProperty(PerfCounter.prototype, "total", {
  9179. get: function () {
  9180. return this._totalAccumulated;
  9181. },
  9182. enumerable: true,
  9183. configurable: true
  9184. });
  9185. Object.defineProperty(PerfCounter.prototype, "count", {
  9186. get: function () {
  9187. return this._totalValueCount;
  9188. },
  9189. enumerable: true,
  9190. configurable: true
  9191. });
  9192. /**
  9193. * Call this method to start monitoring a new frame.
  9194. * 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.
  9195. */
  9196. PerfCounter.prototype.fetchNewFrame = function () {
  9197. this._totalValueCount++;
  9198. this._current = 0;
  9199. this._lastSecValueCount++;
  9200. };
  9201. /**
  9202. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9203. * @param newCount the count value to add to the monitored count
  9204. * @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.
  9205. */
  9206. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9207. if (!PerfCounter.Enabled) {
  9208. return;
  9209. }
  9210. this._current += newCount;
  9211. if (fetchResult) {
  9212. this._fetchResult();
  9213. }
  9214. };
  9215. /**
  9216. * Start monitoring this performance counter
  9217. */
  9218. PerfCounter.prototype.beginMonitoring = function () {
  9219. if (!PerfCounter.Enabled) {
  9220. return;
  9221. }
  9222. this._startMonitoringTime = Tools.Now;
  9223. };
  9224. /**
  9225. * Compute the time lapsed since the previous beginMonitoring() call.
  9226. * @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
  9227. */
  9228. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9229. if (newFrame === void 0) { newFrame = true; }
  9230. if (!PerfCounter.Enabled) {
  9231. return;
  9232. }
  9233. if (newFrame) {
  9234. this.fetchNewFrame();
  9235. }
  9236. var currentTime = Tools.Now;
  9237. this._current = currentTime - this._startMonitoringTime;
  9238. if (newFrame) {
  9239. this._fetchResult();
  9240. }
  9241. };
  9242. PerfCounter.prototype._fetchResult = function () {
  9243. this._totalAccumulated += this._current;
  9244. this._lastSecAccumulated += this._current;
  9245. // Min/Max update
  9246. this._min = Math.min(this._min, this._current);
  9247. this._max = Math.max(this._max, this._current);
  9248. this._average = this._totalAccumulated / this._totalValueCount;
  9249. // Reset last sec?
  9250. var now = Tools.Now;
  9251. if ((now - this._lastSecTime) > 1000) {
  9252. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9253. this._lastSecTime = now;
  9254. this._lastSecAccumulated = 0;
  9255. this._lastSecValueCount = 0;
  9256. }
  9257. };
  9258. PerfCounter.Enabled = true;
  9259. return PerfCounter;
  9260. }());
  9261. BABYLON.PerfCounter = PerfCounter;
  9262. /**
  9263. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9264. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9265. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9266. * @param name The name of the class, case should be preserved
  9267. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9268. */
  9269. function className(name, module) {
  9270. return function (target) {
  9271. target["__bjsclassName__"] = name;
  9272. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9273. };
  9274. }
  9275. BABYLON.className = className;
  9276. /**
  9277. * An implementation of a loop for asynchronous functions.
  9278. */
  9279. var AsyncLoop = /** @class */ (function () {
  9280. /**
  9281. * Constroctor.
  9282. * @param iterations the number of iterations.
  9283. * @param _fn the function to run each iteration
  9284. * @param _successCallback the callback that will be called upon succesful execution
  9285. * @param offset starting offset.
  9286. */
  9287. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9288. if (offset === void 0) { offset = 0; }
  9289. this.iterations = iterations;
  9290. this._fn = _fn;
  9291. this._successCallback = _successCallback;
  9292. this.index = offset - 1;
  9293. this._done = false;
  9294. }
  9295. /**
  9296. * Execute the next iteration. Must be called after the last iteration was finished.
  9297. */
  9298. AsyncLoop.prototype.executeNext = function () {
  9299. if (!this._done) {
  9300. if (this.index + 1 < this.iterations) {
  9301. ++this.index;
  9302. this._fn(this);
  9303. }
  9304. else {
  9305. this.breakLoop();
  9306. }
  9307. }
  9308. };
  9309. /**
  9310. * Break the loop and run the success callback.
  9311. */
  9312. AsyncLoop.prototype.breakLoop = function () {
  9313. this._done = true;
  9314. this._successCallback();
  9315. };
  9316. /**
  9317. * Helper function
  9318. */
  9319. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9320. if (offset === void 0) { offset = 0; }
  9321. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9322. loop.executeNext();
  9323. return loop;
  9324. };
  9325. /**
  9326. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9327. * @param iterations total number of iterations
  9328. * @param syncedIterations number of synchronous iterations in each async iteration.
  9329. * @param fn the function to call each iteration.
  9330. * @param callback a success call back that will be called when iterating stops.
  9331. * @param breakFunction a break condition (optional)
  9332. * @param timeout timeout settings for the setTimeout function. default - 0.
  9333. * @constructor
  9334. */
  9335. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9336. if (timeout === void 0) { timeout = 0; }
  9337. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9338. if (breakFunction && breakFunction())
  9339. loop.breakLoop();
  9340. else {
  9341. setTimeout(function () {
  9342. for (var i = 0; i < syncedIterations; ++i) {
  9343. var iteration = (loop.index * syncedIterations) + i;
  9344. if (iteration >= iterations)
  9345. break;
  9346. fn(iteration);
  9347. if (breakFunction && breakFunction()) {
  9348. loop.breakLoop();
  9349. break;
  9350. }
  9351. }
  9352. loop.executeNext();
  9353. }, timeout);
  9354. }
  9355. }, callback);
  9356. };
  9357. return AsyncLoop;
  9358. }());
  9359. BABYLON.AsyncLoop = AsyncLoop;
  9360. })(BABYLON || (BABYLON = {}));
  9361. //# sourceMappingURL=babylon.tools.js.map
  9362. var BABYLON;
  9363. (function (BABYLON) {
  9364. var PromiseStates;
  9365. (function (PromiseStates) {
  9366. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9367. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9368. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9369. })(PromiseStates || (PromiseStates = {}));
  9370. var FulFillmentAgregator = /** @class */ (function () {
  9371. function FulFillmentAgregator() {
  9372. this.count = 0;
  9373. this.target = 0;
  9374. this.results = [];
  9375. }
  9376. return FulFillmentAgregator;
  9377. }());
  9378. var InternalPromise = /** @class */ (function () {
  9379. function InternalPromise(resolver) {
  9380. var _this = this;
  9381. this._state = PromiseStates.Pending;
  9382. this._children = new Array();
  9383. this._rejectWasConsumed = false;
  9384. if (!resolver) {
  9385. return;
  9386. }
  9387. try {
  9388. resolver(function (value) {
  9389. _this._resolve(value);
  9390. }, function (reason) {
  9391. _this._reject(reason);
  9392. });
  9393. }
  9394. catch (e) {
  9395. this._reject(e);
  9396. }
  9397. }
  9398. InternalPromise.prototype.catch = function (onRejected) {
  9399. return this.then(undefined, onRejected);
  9400. };
  9401. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9402. var _this = this;
  9403. var newPromise = new InternalPromise();
  9404. newPromise._onFulfilled = onFulfilled;
  9405. newPromise._onRejected = onRejected;
  9406. // Composition
  9407. this._children.push(newPromise);
  9408. if (this._state !== PromiseStates.Pending) {
  9409. BABYLON.Tools.SetImmediate(function () {
  9410. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9411. var returnedValue = newPromise._resolve(_this._result);
  9412. if (returnedValue !== undefined && returnedValue !== null) {
  9413. if (returnedValue._state !== undefined) {
  9414. var returnedPromise = returnedValue;
  9415. newPromise._children.push(returnedPromise);
  9416. newPromise = returnedPromise;
  9417. }
  9418. else {
  9419. newPromise._result = returnedValue;
  9420. }
  9421. }
  9422. }
  9423. else {
  9424. newPromise._reject(_this._reason);
  9425. }
  9426. });
  9427. }
  9428. return newPromise;
  9429. };
  9430. InternalPromise.prototype._moveChildren = function (children) {
  9431. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9432. if (this._state === PromiseStates.Fulfilled) {
  9433. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9434. var child = _b[_i];
  9435. child._resolve(this._result);
  9436. }
  9437. }
  9438. else if (this._state === PromiseStates.Rejected) {
  9439. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9440. var child = _d[_c];
  9441. child._reject(this._reason);
  9442. }
  9443. }
  9444. var _a;
  9445. };
  9446. InternalPromise.prototype._resolve = function (value) {
  9447. try {
  9448. this._state = PromiseStates.Fulfilled;
  9449. this._result = value;
  9450. var returnedValue = null;
  9451. if (this._onFulfilled) {
  9452. returnedValue = this._onFulfilled(value);
  9453. }
  9454. if (returnedValue !== undefined && returnedValue !== null) {
  9455. if (returnedValue._state !== undefined) {
  9456. // Transmit children
  9457. var returnedPromise = returnedValue;
  9458. returnedPromise._moveChildren(this._children);
  9459. }
  9460. else {
  9461. value = returnedValue;
  9462. }
  9463. }
  9464. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9465. var child = _a[_i];
  9466. child._resolve(value);
  9467. }
  9468. this._children.length = 0;
  9469. delete this._onFulfilled;
  9470. delete this._onRejected;
  9471. return returnedValue;
  9472. }
  9473. catch (e) {
  9474. this._reject(e, true);
  9475. }
  9476. return null;
  9477. };
  9478. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9479. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9480. this._state = PromiseStates.Rejected;
  9481. this._reason = reason;
  9482. if (this._onRejected && !onLocalThrow) {
  9483. try {
  9484. this._onRejected(reason);
  9485. this._rejectWasConsumed = true;
  9486. }
  9487. catch (e) {
  9488. reason = e;
  9489. }
  9490. }
  9491. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9492. var child = _a[_i];
  9493. if (this._rejectWasConsumed) {
  9494. child._resolve(null);
  9495. }
  9496. else {
  9497. child._reject(reason);
  9498. }
  9499. }
  9500. this._children.length = 0;
  9501. delete this._onFulfilled;
  9502. delete this._onRejected;
  9503. };
  9504. InternalPromise.resolve = function (value) {
  9505. var newPromise = new InternalPromise();
  9506. newPromise._resolve(value);
  9507. return newPromise;
  9508. };
  9509. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9510. promise.then(function (value) {
  9511. agregator.results[index] = value;
  9512. agregator.count++;
  9513. if (agregator.count === agregator.target) {
  9514. agregator.rootPromise._resolve(agregator.results);
  9515. }
  9516. return null;
  9517. }, function (reason) {
  9518. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9519. agregator.rootPromise._reject(reason);
  9520. }
  9521. });
  9522. };
  9523. InternalPromise.all = function (promises) {
  9524. var newPromise = new InternalPromise();
  9525. var agregator = new FulFillmentAgregator();
  9526. agregator.target = promises.length;
  9527. agregator.rootPromise = newPromise;
  9528. if (promises.length) {
  9529. for (var index = 0; index < promises.length; index++) {
  9530. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9531. }
  9532. }
  9533. else {
  9534. newPromise._resolve([]);
  9535. }
  9536. return newPromise;
  9537. };
  9538. InternalPromise.race = function (promises) {
  9539. var newPromise = new InternalPromise();
  9540. if (promises.length) {
  9541. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9542. var promise = promises_1[_i];
  9543. promise.then(function (value) {
  9544. if (newPromise) {
  9545. newPromise._resolve(value);
  9546. newPromise = null;
  9547. }
  9548. return null;
  9549. }, function (reason) {
  9550. if (newPromise) {
  9551. newPromise._reject(reason);
  9552. newPromise = null;
  9553. }
  9554. });
  9555. }
  9556. }
  9557. return newPromise;
  9558. };
  9559. return InternalPromise;
  9560. }());
  9561. /**
  9562. * Helper class that provides a small promise polyfill
  9563. */
  9564. var PromisePolyfill = /** @class */ (function () {
  9565. function PromisePolyfill() {
  9566. }
  9567. /**
  9568. * Static function used to check if the polyfill is required
  9569. * If this is the case then the function will inject the polyfill to window.Promise
  9570. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9571. */
  9572. PromisePolyfill.Apply = function (force) {
  9573. if (force === void 0) { force = false; }
  9574. if (force || typeof Promise === 'undefined') {
  9575. var root = window;
  9576. root.Promise = InternalPromise;
  9577. }
  9578. };
  9579. return PromisePolyfill;
  9580. }());
  9581. BABYLON.PromisePolyfill = PromisePolyfill;
  9582. })(BABYLON || (BABYLON = {}));
  9583. //# sourceMappingURL=babylon.promise.js.map
  9584. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9585. var BABYLON;
  9586. (function (BABYLON) {
  9587. /**
  9588. * Helper class to push actions to a pool of workers.
  9589. */
  9590. var WorkerPool = /** @class */ (function () {
  9591. /**
  9592. * Constructor
  9593. * @param workers Array of workers to use for actions
  9594. */
  9595. function WorkerPool(workers) {
  9596. this._pendingActions = new Array();
  9597. this._workerInfos = workers.map(function (worker) { return ({
  9598. worker: worker,
  9599. active: false
  9600. }); });
  9601. }
  9602. /**
  9603. * Terminates all workers and clears any pending actions.
  9604. */
  9605. WorkerPool.prototype.dispose = function () {
  9606. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9607. var workerInfo = _a[_i];
  9608. workerInfo.worker.terminate();
  9609. }
  9610. delete this._workerInfos;
  9611. delete this._pendingActions;
  9612. };
  9613. /**
  9614. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9615. * pended until a worker has completed its action.
  9616. * @param action The action to perform. Call onComplete when the action is complete.
  9617. */
  9618. WorkerPool.prototype.push = function (action) {
  9619. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9620. var workerInfo = _a[_i];
  9621. if (!workerInfo.active) {
  9622. this._execute(workerInfo, action);
  9623. return;
  9624. }
  9625. }
  9626. this._pendingActions.push(action);
  9627. };
  9628. WorkerPool.prototype._execute = function (workerInfo, action) {
  9629. var _this = this;
  9630. workerInfo.active = true;
  9631. action(workerInfo.worker, function () {
  9632. workerInfo.active = false;
  9633. var nextAction = _this._pendingActions.shift();
  9634. if (nextAction) {
  9635. _this._execute(workerInfo, nextAction);
  9636. }
  9637. });
  9638. };
  9639. return WorkerPool;
  9640. }());
  9641. BABYLON.WorkerPool = WorkerPool;
  9642. })(BABYLON || (BABYLON = {}));
  9643. //# sourceMappingURL=babylon.workerPool.js.map
  9644. var BABYLON;
  9645. (function (BABYLON) {
  9646. var _AlphaState = /** @class */ (function () {
  9647. /**
  9648. * Initializes the state.
  9649. */
  9650. function _AlphaState() {
  9651. this._isAlphaBlendDirty = false;
  9652. this._isBlendFunctionParametersDirty = false;
  9653. this._isBlendEquationParametersDirty = false;
  9654. this._isBlendConstantsDirty = false;
  9655. this._alphaBlend = false;
  9656. this._blendFunctionParameters = new Array(4);
  9657. this._blendEquationParameters = new Array(2);
  9658. this._blendConstants = new Array(4);
  9659. this.reset();
  9660. }
  9661. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9662. get: function () {
  9663. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9669. get: function () {
  9670. return this._alphaBlend;
  9671. },
  9672. set: function (value) {
  9673. if (this._alphaBlend === value) {
  9674. return;
  9675. }
  9676. this._alphaBlend = value;
  9677. this._isAlphaBlendDirty = true;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9683. if (this._blendConstants[0] === r &&
  9684. this._blendConstants[1] === g &&
  9685. this._blendConstants[2] === b &&
  9686. this._blendConstants[3] === a) {
  9687. return;
  9688. }
  9689. this._blendConstants[0] = r;
  9690. this._blendConstants[1] = g;
  9691. this._blendConstants[2] = b;
  9692. this._blendConstants[3] = a;
  9693. this._isBlendConstantsDirty = true;
  9694. };
  9695. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9696. if (this._blendFunctionParameters[0] === value0 &&
  9697. this._blendFunctionParameters[1] === value1 &&
  9698. this._blendFunctionParameters[2] === value2 &&
  9699. this._blendFunctionParameters[3] === value3) {
  9700. return;
  9701. }
  9702. this._blendFunctionParameters[0] = value0;
  9703. this._blendFunctionParameters[1] = value1;
  9704. this._blendFunctionParameters[2] = value2;
  9705. this._blendFunctionParameters[3] = value3;
  9706. this._isBlendFunctionParametersDirty = true;
  9707. };
  9708. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9709. if (this._blendEquationParameters[0] === rgb &&
  9710. this._blendEquationParameters[1] === alpha) {
  9711. return;
  9712. }
  9713. this._blendEquationParameters[0] = rgb;
  9714. this._blendEquationParameters[1] = alpha;
  9715. this._isBlendEquationParametersDirty = true;
  9716. };
  9717. _AlphaState.prototype.reset = function () {
  9718. this._alphaBlend = false;
  9719. this._blendFunctionParameters[0] = null;
  9720. this._blendFunctionParameters[1] = null;
  9721. this._blendFunctionParameters[2] = null;
  9722. this._blendFunctionParameters[3] = null;
  9723. this._blendEquationParameters[0] = null;
  9724. this._blendEquationParameters[1] = null;
  9725. this._blendConstants[0] = null;
  9726. this._blendConstants[1] = null;
  9727. this._blendConstants[2] = null;
  9728. this._blendConstants[3] = null;
  9729. this._isAlphaBlendDirty = true;
  9730. this._isBlendFunctionParametersDirty = false;
  9731. this._isBlendEquationParametersDirty = false;
  9732. this._isBlendConstantsDirty = false;
  9733. };
  9734. _AlphaState.prototype.apply = function (gl) {
  9735. if (!this.isDirty) {
  9736. return;
  9737. }
  9738. // Alpha blend
  9739. if (this._isAlphaBlendDirty) {
  9740. if (this._alphaBlend) {
  9741. gl.enable(gl.BLEND);
  9742. }
  9743. else {
  9744. gl.disable(gl.BLEND);
  9745. }
  9746. this._isAlphaBlendDirty = false;
  9747. }
  9748. // Alpha function
  9749. if (this._isBlendFunctionParametersDirty) {
  9750. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9751. this._isBlendFunctionParametersDirty = false;
  9752. }
  9753. // Alpha equation
  9754. if (this._isBlendEquationParametersDirty) {
  9755. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9756. this._isBlendEquationParametersDirty = false;
  9757. }
  9758. // Constants
  9759. if (this._isBlendConstantsDirty) {
  9760. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9761. this._isBlendConstantsDirty = false;
  9762. }
  9763. };
  9764. return _AlphaState;
  9765. }());
  9766. BABYLON._AlphaState = _AlphaState;
  9767. })(BABYLON || (BABYLON = {}));
  9768. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9769. var BABYLON;
  9770. (function (BABYLON) {
  9771. var _DepthCullingState = /** @class */ (function () {
  9772. /**
  9773. * Initializes the state.
  9774. */
  9775. function _DepthCullingState() {
  9776. this._isDepthTestDirty = false;
  9777. this._isDepthMaskDirty = false;
  9778. this._isDepthFuncDirty = false;
  9779. this._isCullFaceDirty = false;
  9780. this._isCullDirty = false;
  9781. this._isZOffsetDirty = false;
  9782. this._isFrontFaceDirty = false;
  9783. this.reset();
  9784. }
  9785. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9786. get: function () {
  9787. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9793. get: function () {
  9794. return this._zOffset;
  9795. },
  9796. set: function (value) {
  9797. if (this._zOffset === value) {
  9798. return;
  9799. }
  9800. this._zOffset = value;
  9801. this._isZOffsetDirty = true;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9807. get: function () {
  9808. return this._cullFace;
  9809. },
  9810. set: function (value) {
  9811. if (this._cullFace === value) {
  9812. return;
  9813. }
  9814. this._cullFace = value;
  9815. this._isCullFaceDirty = true;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9821. get: function () {
  9822. return this._cull;
  9823. },
  9824. set: function (value) {
  9825. if (this._cull === value) {
  9826. return;
  9827. }
  9828. this._cull = value;
  9829. this._isCullDirty = true;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9835. get: function () {
  9836. return this._depthFunc;
  9837. },
  9838. set: function (value) {
  9839. if (this._depthFunc === value) {
  9840. return;
  9841. }
  9842. this._depthFunc = value;
  9843. this._isDepthFuncDirty = true;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9849. get: function () {
  9850. return this._depthMask;
  9851. },
  9852. set: function (value) {
  9853. if (this._depthMask === value) {
  9854. return;
  9855. }
  9856. this._depthMask = value;
  9857. this._isDepthMaskDirty = true;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9863. get: function () {
  9864. return this._depthTest;
  9865. },
  9866. set: function (value) {
  9867. if (this._depthTest === value) {
  9868. return;
  9869. }
  9870. this._depthTest = value;
  9871. this._isDepthTestDirty = true;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9877. get: function () {
  9878. return this._frontFace;
  9879. },
  9880. set: function (value) {
  9881. if (this._frontFace === value) {
  9882. return;
  9883. }
  9884. this._frontFace = value;
  9885. this._isFrontFaceDirty = true;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. _DepthCullingState.prototype.reset = function () {
  9891. this._depthMask = true;
  9892. this._depthTest = true;
  9893. this._depthFunc = null;
  9894. this._cullFace = null;
  9895. this._cull = null;
  9896. this._zOffset = 0;
  9897. this._frontFace = null;
  9898. this._isDepthTestDirty = true;
  9899. this._isDepthMaskDirty = true;
  9900. this._isDepthFuncDirty = false;
  9901. this._isCullFaceDirty = false;
  9902. this._isCullDirty = false;
  9903. this._isZOffsetDirty = false;
  9904. this._isFrontFaceDirty = false;
  9905. };
  9906. _DepthCullingState.prototype.apply = function (gl) {
  9907. if (!this.isDirty) {
  9908. return;
  9909. }
  9910. // Cull
  9911. if (this._isCullDirty) {
  9912. if (this.cull) {
  9913. gl.enable(gl.CULL_FACE);
  9914. }
  9915. else {
  9916. gl.disable(gl.CULL_FACE);
  9917. }
  9918. this._isCullDirty = false;
  9919. }
  9920. // Cull face
  9921. if (this._isCullFaceDirty) {
  9922. gl.cullFace(this.cullFace);
  9923. this._isCullFaceDirty = false;
  9924. }
  9925. // Depth mask
  9926. if (this._isDepthMaskDirty) {
  9927. gl.depthMask(this.depthMask);
  9928. this._isDepthMaskDirty = false;
  9929. }
  9930. // Depth test
  9931. if (this._isDepthTestDirty) {
  9932. if (this.depthTest) {
  9933. gl.enable(gl.DEPTH_TEST);
  9934. }
  9935. else {
  9936. gl.disable(gl.DEPTH_TEST);
  9937. }
  9938. this._isDepthTestDirty = false;
  9939. }
  9940. // Depth func
  9941. if (this._isDepthFuncDirty) {
  9942. gl.depthFunc(this.depthFunc);
  9943. this._isDepthFuncDirty = false;
  9944. }
  9945. // zOffset
  9946. if (this._isZOffsetDirty) {
  9947. if (this.zOffset) {
  9948. gl.enable(gl.POLYGON_OFFSET_FILL);
  9949. gl.polygonOffset(this.zOffset, 0);
  9950. }
  9951. else {
  9952. gl.disable(gl.POLYGON_OFFSET_FILL);
  9953. }
  9954. this._isZOffsetDirty = false;
  9955. }
  9956. // Front face
  9957. if (this._isFrontFaceDirty) {
  9958. gl.frontFace(this.frontFace);
  9959. this._isFrontFaceDirty = false;
  9960. }
  9961. };
  9962. return _DepthCullingState;
  9963. }());
  9964. BABYLON._DepthCullingState = _DepthCullingState;
  9965. })(BABYLON || (BABYLON = {}));
  9966. //# sourceMappingURL=babylon.depthCullingState.js.map
  9967. var BABYLON;
  9968. (function (BABYLON) {
  9969. var _StencilState = /** @class */ (function () {
  9970. function _StencilState() {
  9971. this._isStencilTestDirty = false;
  9972. this._isStencilMaskDirty = false;
  9973. this._isStencilFuncDirty = false;
  9974. this._isStencilOpDirty = false;
  9975. this.reset();
  9976. }
  9977. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9978. get: function () {
  9979. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9985. get: function () {
  9986. return this._stencilFunc;
  9987. },
  9988. set: function (value) {
  9989. if (this._stencilFunc === value) {
  9990. return;
  9991. }
  9992. this._stencilFunc = value;
  9993. this._isStencilFuncDirty = true;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9999. get: function () {
  10000. return this._stencilFuncRef;
  10001. },
  10002. set: function (value) {
  10003. if (this._stencilFuncRef === value) {
  10004. return;
  10005. }
  10006. this._stencilFuncRef = value;
  10007. this._isStencilFuncDirty = true;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10013. get: function () {
  10014. return this._stencilFuncMask;
  10015. },
  10016. set: function (value) {
  10017. if (this._stencilFuncMask === value) {
  10018. return;
  10019. }
  10020. this._stencilFuncMask = value;
  10021. this._isStencilFuncDirty = true;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10027. get: function () {
  10028. return this._stencilOpStencilFail;
  10029. },
  10030. set: function (value) {
  10031. if (this._stencilOpStencilFail === value) {
  10032. return;
  10033. }
  10034. this._stencilOpStencilFail = value;
  10035. this._isStencilOpDirty = true;
  10036. },
  10037. enumerable: true,
  10038. configurable: true
  10039. });
  10040. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10041. get: function () {
  10042. return this._stencilOpDepthFail;
  10043. },
  10044. set: function (value) {
  10045. if (this._stencilOpDepthFail === value) {
  10046. return;
  10047. }
  10048. this._stencilOpDepthFail = value;
  10049. this._isStencilOpDirty = true;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10055. get: function () {
  10056. return this._stencilOpStencilDepthPass;
  10057. },
  10058. set: function (value) {
  10059. if (this._stencilOpStencilDepthPass === value) {
  10060. return;
  10061. }
  10062. this._stencilOpStencilDepthPass = value;
  10063. this._isStencilOpDirty = true;
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10069. get: function () {
  10070. return this._stencilMask;
  10071. },
  10072. set: function (value) {
  10073. if (this._stencilMask === value) {
  10074. return;
  10075. }
  10076. this._stencilMask = value;
  10077. this._isStencilMaskDirty = true;
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10083. get: function () {
  10084. return this._stencilTest;
  10085. },
  10086. set: function (value) {
  10087. if (this._stencilTest === value) {
  10088. return;
  10089. }
  10090. this._stencilTest = value;
  10091. this._isStencilTestDirty = true;
  10092. },
  10093. enumerable: true,
  10094. configurable: true
  10095. });
  10096. _StencilState.prototype.reset = function () {
  10097. this._stencilTest = false;
  10098. this._stencilMask = 0xFF;
  10099. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10100. this._stencilFuncRef = 1;
  10101. this._stencilFuncMask = 0xFF;
  10102. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10103. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10104. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10105. this._isStencilTestDirty = true;
  10106. this._isStencilMaskDirty = true;
  10107. this._isStencilFuncDirty = true;
  10108. this._isStencilOpDirty = true;
  10109. };
  10110. _StencilState.prototype.apply = function (gl) {
  10111. if (!this.isDirty) {
  10112. return;
  10113. }
  10114. // Stencil test
  10115. if (this._isStencilTestDirty) {
  10116. if (this.stencilTest) {
  10117. gl.enable(gl.STENCIL_TEST);
  10118. }
  10119. else {
  10120. gl.disable(gl.STENCIL_TEST);
  10121. }
  10122. this._isStencilTestDirty = false;
  10123. }
  10124. // Stencil mask
  10125. if (this._isStencilMaskDirty) {
  10126. gl.stencilMask(this.stencilMask);
  10127. this._isStencilMaskDirty = false;
  10128. }
  10129. // Stencil func
  10130. if (this._isStencilFuncDirty) {
  10131. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10132. this._isStencilFuncDirty = false;
  10133. }
  10134. // Stencil op
  10135. if (this._isStencilOpDirty) {
  10136. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10137. this._isStencilOpDirty = false;
  10138. }
  10139. };
  10140. return _StencilState;
  10141. }());
  10142. BABYLON._StencilState = _StencilState;
  10143. })(BABYLON || (BABYLON = {}));
  10144. //# sourceMappingURL=babylon.stencilState.js.map
  10145. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10146. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10147. s = arguments[i];
  10148. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10149. t[p] = s[p];
  10150. }
  10151. return t;
  10152. };
  10153. var BABYLON;
  10154. (function (BABYLON) {
  10155. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10156. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10157. };
  10158. var compileRawShader = function (gl, source, type) {
  10159. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10160. gl.shaderSource(shader, source);
  10161. gl.compileShader(shader);
  10162. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10163. var log = gl.getShaderInfoLog(shader);
  10164. if (log) {
  10165. throw new Error(log);
  10166. }
  10167. }
  10168. if (!shader) {
  10169. throw new Error("Something went wrong while compile the shader.");
  10170. }
  10171. return shader;
  10172. };
  10173. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10174. var magFilter = gl.NEAREST;
  10175. var minFilter = gl.NEAREST;
  10176. switch (samplingMode) {
  10177. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10178. magFilter = gl.LINEAR;
  10179. if (generateMipMaps) {
  10180. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10181. }
  10182. else {
  10183. minFilter = gl.LINEAR;
  10184. }
  10185. break;
  10186. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10187. magFilter = gl.LINEAR;
  10188. if (generateMipMaps) {
  10189. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10190. }
  10191. else {
  10192. minFilter = gl.LINEAR;
  10193. }
  10194. break;
  10195. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10196. magFilter = gl.NEAREST;
  10197. if (generateMipMaps) {
  10198. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10199. }
  10200. else {
  10201. minFilter = gl.NEAREST;
  10202. }
  10203. break;
  10204. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10205. magFilter = gl.NEAREST;
  10206. if (generateMipMaps) {
  10207. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10208. }
  10209. else {
  10210. minFilter = gl.NEAREST;
  10211. }
  10212. break;
  10213. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10214. magFilter = gl.NEAREST;
  10215. if (generateMipMaps) {
  10216. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10217. }
  10218. else {
  10219. minFilter = gl.LINEAR;
  10220. }
  10221. break;
  10222. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10223. magFilter = gl.NEAREST;
  10224. if (generateMipMaps) {
  10225. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10226. }
  10227. else {
  10228. minFilter = gl.LINEAR;
  10229. }
  10230. break;
  10231. case BABYLON.Texture.NEAREST_LINEAR:
  10232. magFilter = gl.NEAREST;
  10233. minFilter = gl.LINEAR;
  10234. break;
  10235. case BABYLON.Texture.NEAREST_NEAREST:
  10236. magFilter = gl.NEAREST;
  10237. minFilter = gl.NEAREST;
  10238. break;
  10239. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10240. magFilter = gl.LINEAR;
  10241. if (generateMipMaps) {
  10242. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10243. }
  10244. else {
  10245. minFilter = gl.NEAREST;
  10246. }
  10247. break;
  10248. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10249. magFilter = gl.LINEAR;
  10250. if (generateMipMaps) {
  10251. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10252. }
  10253. else {
  10254. minFilter = gl.NEAREST;
  10255. }
  10256. break;
  10257. case BABYLON.Texture.LINEAR_LINEAR:
  10258. magFilter = gl.LINEAR;
  10259. minFilter = gl.LINEAR;
  10260. break;
  10261. case BABYLON.Texture.LINEAR_NEAREST:
  10262. magFilter = gl.LINEAR;
  10263. minFilter = gl.NEAREST;
  10264. break;
  10265. }
  10266. return {
  10267. min: minFilter,
  10268. mag: magFilter
  10269. };
  10270. };
  10271. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10272. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10273. var img;
  10274. var onload = function () {
  10275. loadedImages[index] = img;
  10276. loadedImages._internalCount++;
  10277. if (scene) {
  10278. scene._removePendingData(img);
  10279. }
  10280. if (loadedImages._internalCount === 6) {
  10281. onfinish(loadedImages);
  10282. }
  10283. };
  10284. var onerror = function (message, exception) {
  10285. if (scene) {
  10286. scene._removePendingData(img);
  10287. }
  10288. if (onErrorCallBack) {
  10289. onErrorCallBack(message, exception);
  10290. }
  10291. };
  10292. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10293. if (scene) {
  10294. scene._addPendingData(img);
  10295. }
  10296. };
  10297. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10298. if (onError === void 0) { onError = null; }
  10299. var loadedImages = [];
  10300. loadedImages._internalCount = 0;
  10301. for (var index = 0; index < 6; index++) {
  10302. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10303. }
  10304. };
  10305. var BufferPointer = /** @class */ (function () {
  10306. function BufferPointer() {
  10307. }
  10308. return BufferPointer;
  10309. }());
  10310. var InstancingAttributeInfo = /** @class */ (function () {
  10311. function InstancingAttributeInfo() {
  10312. }
  10313. return InstancingAttributeInfo;
  10314. }());
  10315. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10316. /**
  10317. * Define options used to create a render target texture
  10318. */
  10319. var RenderTargetCreationOptions = /** @class */ (function () {
  10320. function RenderTargetCreationOptions() {
  10321. }
  10322. return RenderTargetCreationOptions;
  10323. }());
  10324. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10325. /**
  10326. * Define options used to create a depth texture
  10327. */
  10328. var DepthTextureCreationOptions = /** @class */ (function () {
  10329. function DepthTextureCreationOptions() {
  10330. }
  10331. return DepthTextureCreationOptions;
  10332. }());
  10333. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10334. /**
  10335. * Regroup several parameters relative to the browser in use
  10336. */
  10337. var EngineCapabilities = /** @class */ (function () {
  10338. function EngineCapabilities() {
  10339. }
  10340. return EngineCapabilities;
  10341. }());
  10342. BABYLON.EngineCapabilities = EngineCapabilities;
  10343. /**
  10344. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10345. */
  10346. var Engine = /** @class */ (function () {
  10347. /**
  10348. * @constructor
  10349. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10350. * @param antialias defines enable antialiasing (default: false)
  10351. * @param options defines further options to be sent to the getContext() function
  10352. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10353. */
  10354. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10355. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10356. var _this = this;
  10357. // Public members
  10358. this.forcePOTTextures = false;
  10359. this.isFullscreen = false;
  10360. this.isPointerLock = false;
  10361. this.cullBackFaces = true;
  10362. this.renderEvenInBackground = true;
  10363. this.preventCacheWipeBetweenFrames = false;
  10364. // To enable/disable IDB support and avoid XHR on .manifest
  10365. this.enableOfflineSupport = false;
  10366. this.scenes = new Array();
  10367. this.postProcesses = new Array();
  10368. // Observables
  10369. /**
  10370. * Observable event triggered each time the rendering canvas is resized
  10371. */
  10372. this.onResizeObservable = new BABYLON.Observable();
  10373. /**
  10374. * Observable event triggered each time the canvas loses focus
  10375. */
  10376. this.onCanvasBlurObservable = new BABYLON.Observable();
  10377. /**
  10378. * Observable event triggered each time the canvas gains focus
  10379. */
  10380. this.onCanvasFocusObservable = new BABYLON.Observable();
  10381. /**
  10382. * Observable event triggered each time the canvas receives pointerout event
  10383. */
  10384. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10385. /**
  10386. * Observable event triggered before each texture is initialized
  10387. */
  10388. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10389. //WebVR
  10390. this._vrDisplay = undefined;
  10391. this._vrSupported = false;
  10392. this._vrExclusivePointerMode = false;
  10393. // Uniform buffers list
  10394. this.disableUniformBuffers = false;
  10395. this._uniformBuffers = new Array();
  10396. // Observables
  10397. /**
  10398. * Observable raised when the engine begins a new frame
  10399. */
  10400. this.onBeginFrameObservable = new BABYLON.Observable();
  10401. /**
  10402. * Observable raised when the engine ends the current frame
  10403. */
  10404. this.onEndFrameObservable = new BABYLON.Observable();
  10405. /**
  10406. * Observable raised when the engine is about to compile a shader
  10407. */
  10408. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10409. /**
  10410. * Observable raised when the engine has jsut compiled a shader
  10411. */
  10412. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10413. this._windowIsBackground = false;
  10414. this._webGLVersion = 1.0;
  10415. this._badOS = false;
  10416. this._badDesktopOS = false;
  10417. /**
  10418. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10419. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10420. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10421. */
  10422. this.disableTextureBindingOptimization = false;
  10423. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10424. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10425. this.onVRRequestPresentStart = new BABYLON.Observable();
  10426. this._colorWrite = true;
  10427. this._drawCalls = new BABYLON.PerfCounter();
  10428. this._textureCollisions = new BABYLON.PerfCounter();
  10429. this._renderingQueueLaunched = false;
  10430. this._activeRenderLoops = new Array();
  10431. // Deterministic lockstepMaxSteps
  10432. this._deterministicLockstep = false;
  10433. this._lockstepMaxSteps = 4;
  10434. // Lost context
  10435. this.onContextLostObservable = new BABYLON.Observable();
  10436. this.onContextRestoredObservable = new BABYLON.Observable();
  10437. this._contextWasLost = false;
  10438. this._doNotHandleContextLost = false;
  10439. // FPS
  10440. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10441. this._fps = 60;
  10442. this._deltaTime = 0;
  10443. /**
  10444. * Turn this value on if you want to pause FPS computation when in background
  10445. */
  10446. this.disablePerformanceMonitorInBackground = false;
  10447. // States
  10448. this._depthCullingState = new BABYLON._DepthCullingState();
  10449. this._stencilState = new BABYLON._StencilState();
  10450. this._alphaState = new BABYLON._AlphaState();
  10451. this._alphaMode = Engine.ALPHA_DISABLE;
  10452. // Cache
  10453. this._internalTexturesCache = new Array();
  10454. this._activeChannel = 0;
  10455. this._currentTextureChannel = -1;
  10456. this._boundTexturesCache = {};
  10457. this._compiledEffects = {};
  10458. this._vertexAttribArraysEnabled = [];
  10459. this._uintIndicesCurrentlySet = false;
  10460. this._currentBoundBuffer = new Array();
  10461. this._currentBufferPointers = new Array();
  10462. this._currentInstanceLocations = new Array();
  10463. this._currentInstanceBuffers = new Array();
  10464. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10465. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10466. this._vaoRecordInProgress = false;
  10467. this._mustWipeVertexAttributes = false;
  10468. this._nextFreeTextureSlots = new Array();
  10469. this._maxSimultaneousTextures = 0;
  10470. this._activeRequests = new Array();
  10471. // Hardware supported Compressed Textures
  10472. this._texturesSupported = new Array();
  10473. this._onVRFullScreenTriggered = function () {
  10474. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10475. //get the old size before we change
  10476. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10477. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10478. //get the width and height, change the render size
  10479. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10480. _this.setHardwareScalingLevel(1);
  10481. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10482. }
  10483. else {
  10484. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10485. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10486. }
  10487. };
  10488. this._boundUniforms = {};
  10489. // Register promises
  10490. BABYLON.PromisePolyfill.Apply();
  10491. var canvas = null;
  10492. Engine.Instances.push(this);
  10493. if (!canvasOrContext) {
  10494. return;
  10495. }
  10496. options = options || {};
  10497. if (canvasOrContext.getContext) {
  10498. canvas = canvasOrContext;
  10499. this._renderingCanvas = canvas;
  10500. if (antialias != null) {
  10501. options.antialias = antialias;
  10502. }
  10503. if (options.deterministicLockstep === undefined) {
  10504. options.deterministicLockstep = false;
  10505. }
  10506. if (options.lockstepMaxSteps === undefined) {
  10507. options.lockstepMaxSteps = 4;
  10508. }
  10509. if (options.preserveDrawingBuffer === undefined) {
  10510. options.preserveDrawingBuffer = false;
  10511. }
  10512. if (options.audioEngine === undefined) {
  10513. options.audioEngine = true;
  10514. }
  10515. if (options.stencil === undefined) {
  10516. options.stencil = true;
  10517. }
  10518. this._deterministicLockstep = options.deterministicLockstep;
  10519. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10520. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10521. // Exceptions
  10522. if (navigator && navigator.userAgent) {
  10523. var ua = navigator.userAgent;
  10524. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10525. var exception = _a[_i];
  10526. var key = exception.key;
  10527. var targets = exception.targets;
  10528. if (ua.indexOf(key) > -1) {
  10529. if (exception.capture && exception.captureConstraint) {
  10530. var capture = exception.capture;
  10531. var constraint = exception.captureConstraint;
  10532. var regex = new RegExp(capture);
  10533. var matches = regex.exec(ua);
  10534. if (matches && matches.length > 0) {
  10535. var capturedValue = parseInt(matches[matches.length - 1]);
  10536. if (capturedValue >= constraint) {
  10537. continue;
  10538. }
  10539. }
  10540. }
  10541. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10542. var target = targets_1[_b];
  10543. switch (target) {
  10544. case "uniformBuffer":
  10545. this.disableUniformBuffers = true;
  10546. break;
  10547. case "textureBindingOptimization":
  10548. this.disableTextureBindingOptimization = true;
  10549. break;
  10550. }
  10551. }
  10552. }
  10553. }
  10554. }
  10555. // GL
  10556. if (!options.disableWebGL2Support) {
  10557. try {
  10558. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10559. if (this._gl) {
  10560. this._webGLVersion = 2.0;
  10561. }
  10562. }
  10563. catch (e) {
  10564. // Do nothing
  10565. }
  10566. }
  10567. if (!this._gl) {
  10568. if (!canvas) {
  10569. throw new Error("The provided canvas is null or undefined.");
  10570. }
  10571. try {
  10572. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10573. }
  10574. catch (e) {
  10575. throw new Error("WebGL not supported");
  10576. }
  10577. }
  10578. if (!this._gl) {
  10579. throw new Error("WebGL not supported");
  10580. }
  10581. this._onCanvasFocus = function () {
  10582. _this.onCanvasFocusObservable.notifyObservers(_this);
  10583. };
  10584. this._onCanvasBlur = function () {
  10585. _this.onCanvasBlurObservable.notifyObservers(_this);
  10586. };
  10587. canvas.addEventListener("focus", this._onCanvasFocus);
  10588. canvas.addEventListener("blur", this._onCanvasBlur);
  10589. this._onBlur = function () {
  10590. if (_this.disablePerformanceMonitorInBackground) {
  10591. _this._performanceMonitor.disable();
  10592. }
  10593. _this._windowIsBackground = true;
  10594. };
  10595. this._onFocus = function () {
  10596. if (_this.disablePerformanceMonitorInBackground) {
  10597. _this._performanceMonitor.enable();
  10598. }
  10599. _this._windowIsBackground = false;
  10600. };
  10601. this._onCanvasPointerOut = function (ev) {
  10602. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10603. };
  10604. window.addEventListener("blur", this._onBlur);
  10605. window.addEventListener("focus", this._onFocus);
  10606. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10607. // Context lost
  10608. if (!this._doNotHandleContextLost) {
  10609. this._onContextLost = function (evt) {
  10610. evt.preventDefault();
  10611. _this._contextWasLost = true;
  10612. BABYLON.Tools.Warn("WebGL context lost.");
  10613. _this.onContextLostObservable.notifyObservers(_this);
  10614. };
  10615. this._onContextRestored = function (evt) {
  10616. // Adding a timeout to avoid race condition at browser level
  10617. setTimeout(function () {
  10618. // Rebuild gl context
  10619. _this._initGLContext();
  10620. // Rebuild effects
  10621. _this._rebuildEffects();
  10622. // Rebuild textures
  10623. _this._rebuildInternalTextures();
  10624. // Rebuild buffers
  10625. _this._rebuildBuffers();
  10626. // Cache
  10627. _this.wipeCaches(true);
  10628. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10629. _this.onContextRestoredObservable.notifyObservers(_this);
  10630. _this._contextWasLost = false;
  10631. }, 0);
  10632. };
  10633. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10634. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10635. }
  10636. }
  10637. else {
  10638. this._gl = canvasOrContext;
  10639. this._renderingCanvas = this._gl.canvas;
  10640. if (this._gl.renderbufferStorageMultisample) {
  10641. this._webGLVersion = 2.0;
  10642. }
  10643. options.stencil = this._gl.getContextAttributes().stencil;
  10644. }
  10645. // Viewport
  10646. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10647. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10648. this.resize();
  10649. this._isStencilEnable = options.stencil ? true : false;
  10650. this._initGLContext();
  10651. if (canvas) {
  10652. // Fullscreen
  10653. this._onFullscreenChange = function () {
  10654. if (document.fullscreen !== undefined) {
  10655. _this.isFullscreen = document.fullscreen;
  10656. }
  10657. else if (document.mozFullScreen !== undefined) {
  10658. _this.isFullscreen = document.mozFullScreen;
  10659. }
  10660. else if (document.webkitIsFullScreen !== undefined) {
  10661. _this.isFullscreen = document.webkitIsFullScreen;
  10662. }
  10663. else if (document.msIsFullScreen !== undefined) {
  10664. _this.isFullscreen = document.msIsFullScreen;
  10665. }
  10666. // Pointer lock
  10667. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10668. canvas.requestPointerLock = canvas.requestPointerLock ||
  10669. canvas.msRequestPointerLock ||
  10670. canvas.mozRequestPointerLock ||
  10671. canvas.webkitRequestPointerLock;
  10672. if (canvas.requestPointerLock) {
  10673. canvas.requestPointerLock();
  10674. }
  10675. }
  10676. };
  10677. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10678. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10679. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10680. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10681. // Pointer lock
  10682. this._onPointerLockChange = function () {
  10683. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10684. document.webkitPointerLockElement === canvas ||
  10685. document.msPointerLockElement === canvas ||
  10686. document.pointerLockElement === canvas);
  10687. };
  10688. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10689. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10690. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10691. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10692. this._onVRDisplayPointerRestricted = function () {
  10693. if (canvas) {
  10694. canvas.requestPointerLock();
  10695. }
  10696. };
  10697. this._onVRDisplayPointerUnrestricted = function () {
  10698. document.exitPointerLock();
  10699. };
  10700. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10701. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10702. }
  10703. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10704. Engine.audioEngine = new BABYLON.AudioEngine();
  10705. }
  10706. // Prepare buffer pointers
  10707. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10708. this._currentBufferPointers[i] = new BufferPointer();
  10709. }
  10710. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10711. // Load WebVR Devices
  10712. if (options.autoEnableWebVR) {
  10713. this.initWebVR();
  10714. }
  10715. // Detect if we are running on a faulty buggy OS.
  10716. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10717. // Detect if we are running on a faulty buggy desktop OS.
  10718. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10719. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10720. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10721. }
  10722. Object.defineProperty(Engine, "LastCreatedEngine", {
  10723. get: function () {
  10724. if (Engine.Instances.length === 0) {
  10725. return null;
  10726. }
  10727. return Engine.Instances[Engine.Instances.length - 1];
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "LastCreatedScene", {
  10733. get: function () {
  10734. var lastCreatedEngine = Engine.LastCreatedEngine;
  10735. if (!lastCreatedEngine) {
  10736. return null;
  10737. }
  10738. if (lastCreatedEngine.scenes.length === 0) {
  10739. return null;
  10740. }
  10741. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. /**
  10747. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10748. */
  10749. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10750. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10751. var engine = Engine.Instances[engineIndex];
  10752. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10753. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10754. }
  10755. }
  10756. };
  10757. Object.defineProperty(Engine, "NEVER", {
  10758. get: function () {
  10759. return Engine._NEVER;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Engine, "ALWAYS", {
  10765. get: function () {
  10766. return Engine._ALWAYS;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(Engine, "LESS", {
  10772. get: function () {
  10773. return Engine._LESS;
  10774. },
  10775. enumerable: true,
  10776. configurable: true
  10777. });
  10778. Object.defineProperty(Engine, "EQUAL", {
  10779. get: function () {
  10780. return Engine._EQUAL;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(Engine, "LEQUAL", {
  10786. get: function () {
  10787. return Engine._LEQUAL;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine, "GREATER", {
  10793. get: function () {
  10794. return Engine._GREATER;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine, "GEQUAL", {
  10800. get: function () {
  10801. return Engine._GEQUAL;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Object.defineProperty(Engine, "NOTEQUAL", {
  10807. get: function () {
  10808. return Engine._NOTEQUAL;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "KEEP", {
  10814. get: function () {
  10815. return Engine._KEEP;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "REPLACE", {
  10821. get: function () {
  10822. return Engine._REPLACE;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(Engine, "INCR", {
  10828. get: function () {
  10829. return Engine._INCR;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "DECR", {
  10835. get: function () {
  10836. return Engine._DECR;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(Engine, "INVERT", {
  10842. get: function () {
  10843. return Engine._INVERT;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "INCR_WRAP", {
  10849. get: function () {
  10850. return Engine._INCR_WRAP;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "DECR_WRAP", {
  10856. get: function () {
  10857. return Engine._DECR_WRAP;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10863. get: function () {
  10864. return Engine._ALPHA_DISABLE;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10870. get: function () {
  10871. return Engine._ALPHA_ONEONE;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "ALPHA_ADD", {
  10877. get: function () {
  10878. return Engine._ALPHA_ADD;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10884. get: function () {
  10885. return Engine._ALPHA_COMBINE;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10891. get: function () {
  10892. return Engine._ALPHA_SUBTRACT;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10898. get: function () {
  10899. return Engine._ALPHA_MULTIPLY;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10905. get: function () {
  10906. return Engine._ALPHA_MAXIMIZED;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10912. get: function () {
  10913. return Engine._ALPHA_PREMULTIPLIED;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10919. get: function () {
  10920. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10926. get: function () {
  10927. return Engine._ALPHA_INTERPOLATE;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10933. get: function () {
  10934. return Engine._ALPHA_SCREENMODE;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10940. get: function () {
  10941. return Engine._DELAYLOADSTATE_NONE;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10947. get: function () {
  10948. return Engine._DELAYLOADSTATE_LOADED;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10954. get: function () {
  10955. return Engine._DELAYLOADSTATE_LOADING;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10961. get: function () {
  10962. return Engine._DELAYLOADSTATE_NOTLOADED;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10968. get: function () {
  10969. return Engine._TEXTUREFORMAT_ALPHA;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10975. get: function () {
  10976. return Engine._TEXTUREFORMAT_LUMINANCE;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10982. /**
  10983. * R32F
  10984. */
  10985. get: function () {
  10986. return Engine._TEXTUREFORMAT_R32F;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10992. /**
  10993. * RG32F
  10994. */
  10995. get: function () {
  10996. return Engine._TEXTUREFORMAT_RG32F;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11002. /**
  11003. * RGB32F
  11004. */
  11005. get: function () {
  11006. return Engine._TEXTUREFORMAT_RGB32F;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11012. /**
  11013. * RGBA32F
  11014. */
  11015. get: function () {
  11016. return Engine._TEXTUREFORMAT_RGBA32F;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11022. get: function () {
  11023. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11029. get: function () {
  11030. return Engine._TEXTUREFORMAT_RGB;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11036. get: function () {
  11037. return Engine._TEXTUREFORMAT_RGBA;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11043. get: function () {
  11044. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11050. get: function () {
  11051. return Engine._TEXTURETYPE_FLOAT;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11057. get: function () {
  11058. return Engine._TEXTURETYPE_HALF_FLOAT;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11064. get: function () {
  11065. return Engine._SCALEMODE_FLOOR;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11071. get: function () {
  11072. return Engine._SCALEMODE_NEAREST;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11078. get: function () {
  11079. return Engine._SCALEMODE_CEILING;
  11080. },
  11081. enumerable: true,
  11082. configurable: true
  11083. });
  11084. Object.defineProperty(Engine, "Version", {
  11085. get: function () {
  11086. return "3.2.0-alphaB";
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11092. get: function () {
  11093. return this._vrExclusivePointerMode;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11099. get: function () {
  11100. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11106. get: function () {
  11107. return this._webGLVersion < 2 || this.forcePOTTextures;
  11108. },
  11109. enumerable: true,
  11110. configurable: true
  11111. });
  11112. Object.defineProperty(Engine.prototype, "badOS", {
  11113. get: function () {
  11114. return this._badOS;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11120. get: function () {
  11121. return this._badDesktopOS;
  11122. },
  11123. enumerable: true,
  11124. configurable: true
  11125. });
  11126. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11127. get: function () {
  11128. return this._performanceMonitor;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11134. get: function () {
  11135. return this._texturesSupported;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11141. get: function () {
  11142. return this._textureFormatInUse;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(Engine.prototype, "currentViewport", {
  11148. get: function () {
  11149. return this._cachedViewport;
  11150. },
  11151. enumerable: true,
  11152. configurable: true
  11153. });
  11154. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11155. // Empty texture
  11156. get: function () {
  11157. if (!this._emptyTexture) {
  11158. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11159. }
  11160. return this._emptyTexture;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11166. get: function () {
  11167. if (!this._emptyTexture3D) {
  11168. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11169. }
  11170. return this._emptyTexture3D;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11176. get: function () {
  11177. if (!this._emptyCubeTexture) {
  11178. var faceData = new Uint8Array(4);
  11179. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11180. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11181. }
  11182. return this._emptyCubeTexture;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Engine.prototype._rebuildInternalTextures = function () {
  11188. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11189. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11190. var internalTexture = currentState_1[_i];
  11191. internalTexture._rebuild();
  11192. }
  11193. };
  11194. Engine.prototype._rebuildEffects = function () {
  11195. for (var key in this._compiledEffects) {
  11196. var effect = this._compiledEffects[key];
  11197. effect._prepareEffect();
  11198. }
  11199. BABYLON.Effect.ResetCache();
  11200. };
  11201. Engine.prototype._rebuildBuffers = function () {
  11202. // Index / Vertex
  11203. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11204. var scene = _a[_i];
  11205. scene.resetCachedMaterial();
  11206. scene._rebuildGeometries();
  11207. scene._rebuildTextures();
  11208. }
  11209. // Uniforms
  11210. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11211. var uniformBuffer = _c[_b];
  11212. uniformBuffer._rebuild();
  11213. }
  11214. };
  11215. Engine.prototype._initGLContext = function () {
  11216. // Caps
  11217. this._caps = new EngineCapabilities();
  11218. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11219. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11220. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11221. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11222. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11223. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11224. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11225. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11226. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11227. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11228. // Infos
  11229. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11230. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11231. if (rendererInfo != null) {
  11232. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11233. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11234. }
  11235. if (!this._glVendor) {
  11236. this._glVendor = "Unknown vendor";
  11237. }
  11238. if (!this._glRenderer) {
  11239. this._glRenderer = "Unknown renderer";
  11240. }
  11241. // Constants
  11242. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11243. if (this._gl.RGBA16F !== 0x881A) {
  11244. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11245. }
  11246. if (this._gl.RGBA32F !== 0x8814) {
  11247. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11248. }
  11249. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11250. this._gl.DEPTH24_STENCIL8 = 35056;
  11251. }
  11252. // Extensions
  11253. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11254. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11255. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11256. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11257. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11258. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11259. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11260. 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');
  11261. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11262. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11263. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11264. this._caps.highPrecisionShaderSupported = true;
  11265. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11266. if (this._caps.timerQuery) {
  11267. if (this._webGLVersion === 1) {
  11268. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11269. }
  11270. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11271. }
  11272. // Checks if some of the format renders first to allow the use of webgl inspector.
  11273. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11274. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11275. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11276. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11277. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11278. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11279. if (this._webGLVersion > 1) {
  11280. this._gl.HALF_FLOAT_OES = 0x140B;
  11281. }
  11282. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11283. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11284. // Draw buffers
  11285. if (this._webGLVersion > 1) {
  11286. this._caps.drawBuffersExtension = true;
  11287. }
  11288. else {
  11289. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11290. if (drawBuffersExtension !== null) {
  11291. this._caps.drawBuffersExtension = true;
  11292. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11293. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11294. for (var i = 0; i < 16; i++) {
  11295. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11296. }
  11297. }
  11298. else {
  11299. this._caps.drawBuffersExtension = false;
  11300. }
  11301. }
  11302. // Depth Texture
  11303. if (this._webGLVersion > 1) {
  11304. this._caps.depthTextureExtension = true;
  11305. }
  11306. else {
  11307. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11308. if (depthTextureExtension != null) {
  11309. this._caps.depthTextureExtension = true;
  11310. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11311. }
  11312. }
  11313. // Vertex array object
  11314. if (this._webGLVersion > 1) {
  11315. this._caps.vertexArrayObject = true;
  11316. }
  11317. else {
  11318. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11319. if (vertexArrayObjectExtension != null) {
  11320. this._caps.vertexArrayObject = true;
  11321. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11322. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11323. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11324. }
  11325. else {
  11326. this._caps.vertexArrayObject = false;
  11327. }
  11328. }
  11329. // Instances count
  11330. if (this._webGLVersion > 1) {
  11331. this._caps.instancedArrays = true;
  11332. }
  11333. else {
  11334. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11335. if (instanceExtension != null) {
  11336. this._caps.instancedArrays = true;
  11337. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11338. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11339. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11340. }
  11341. else {
  11342. this._caps.instancedArrays = false;
  11343. }
  11344. }
  11345. // Intelligently add supported compressed formats in order to check for.
  11346. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11347. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11348. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11349. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11350. if (this._caps.astc)
  11351. this.texturesSupported.push('-astc.ktx');
  11352. if (this._caps.s3tc)
  11353. this.texturesSupported.push('-dxt.ktx');
  11354. if (this._caps.pvrtc)
  11355. this.texturesSupported.push('-pvrtc.ktx');
  11356. if (this._caps.etc2)
  11357. this.texturesSupported.push('-etc2.ktx');
  11358. if (this._caps.etc1)
  11359. this.texturesSupported.push('-etc1.ktx');
  11360. if (this._gl.getShaderPrecisionFormat) {
  11361. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11362. if (highp) {
  11363. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11364. }
  11365. }
  11366. // Depth buffer
  11367. this.setDepthBuffer(true);
  11368. this.setDepthFunctionToLessOrEqual();
  11369. this.setDepthWrite(true);
  11370. // Texture maps
  11371. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11372. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11373. this._nextFreeTextureSlots.push(slot);
  11374. }
  11375. };
  11376. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11377. get: function () {
  11378. return this._webGLVersion;
  11379. },
  11380. enumerable: true,
  11381. configurable: true
  11382. });
  11383. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11384. /**
  11385. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11386. */
  11387. get: function () {
  11388. return this._isStencilEnable;
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. Engine.prototype._prepareWorkingCanvas = function () {
  11394. if (this._workingCanvas) {
  11395. return;
  11396. }
  11397. this._workingCanvas = document.createElement("canvas");
  11398. var context = this._workingCanvas.getContext("2d");
  11399. if (context) {
  11400. this._workingContext = context;
  11401. }
  11402. };
  11403. Engine.prototype.resetTextureCache = function () {
  11404. for (var key in this._boundTexturesCache) {
  11405. var boundTexture = this._boundTexturesCache[key];
  11406. if (boundTexture) {
  11407. this._removeDesignatedSlot(boundTexture);
  11408. }
  11409. this._boundTexturesCache[key] = null;
  11410. }
  11411. if (!this.disableTextureBindingOptimization) {
  11412. this._nextFreeTextureSlots = [];
  11413. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11414. this._nextFreeTextureSlots.push(slot);
  11415. }
  11416. }
  11417. this._currentTextureChannel = -1;
  11418. };
  11419. Engine.prototype.isDeterministicLockStep = function () {
  11420. return this._deterministicLockstep;
  11421. };
  11422. Engine.prototype.getLockstepMaxSteps = function () {
  11423. return this._lockstepMaxSteps;
  11424. };
  11425. Engine.prototype.getGlInfo = function () {
  11426. return {
  11427. vendor: this._glVendor,
  11428. renderer: this._glRenderer,
  11429. version: this._glVersion
  11430. };
  11431. };
  11432. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11433. if (useScreen === void 0) { useScreen = false; }
  11434. var viewport = camera.viewport;
  11435. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11436. };
  11437. Engine.prototype.getRenderWidth = function (useScreen) {
  11438. if (useScreen === void 0) { useScreen = false; }
  11439. if (!useScreen && this._currentRenderTarget) {
  11440. return this._currentRenderTarget.width;
  11441. }
  11442. return this._gl.drawingBufferWidth;
  11443. };
  11444. Engine.prototype.getRenderHeight = function (useScreen) {
  11445. if (useScreen === void 0) { useScreen = false; }
  11446. if (!useScreen && this._currentRenderTarget) {
  11447. return this._currentRenderTarget.height;
  11448. }
  11449. return this._gl.drawingBufferHeight;
  11450. };
  11451. Engine.prototype.getRenderingCanvas = function () {
  11452. return this._renderingCanvas;
  11453. };
  11454. Engine.prototype.getRenderingCanvasClientRect = function () {
  11455. if (!this._renderingCanvas) {
  11456. return null;
  11457. }
  11458. return this._renderingCanvas.getBoundingClientRect();
  11459. };
  11460. Engine.prototype.setHardwareScalingLevel = function (level) {
  11461. this._hardwareScalingLevel = level;
  11462. this.resize();
  11463. };
  11464. Engine.prototype.getHardwareScalingLevel = function () {
  11465. return this._hardwareScalingLevel;
  11466. };
  11467. Engine.prototype.getLoadedTexturesCache = function () {
  11468. return this._internalTexturesCache;
  11469. };
  11470. Engine.prototype.getCaps = function () {
  11471. return this._caps;
  11472. };
  11473. Object.defineProperty(Engine.prototype, "drawCalls", {
  11474. /** The number of draw calls submitted last frame */
  11475. get: function () {
  11476. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11477. return 0;
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11483. get: function () {
  11484. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11485. return null;
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Engine.prototype.getDepthFunction = function () {
  11491. return this._depthCullingState.depthFunc;
  11492. };
  11493. Engine.prototype.setDepthFunction = function (depthFunc) {
  11494. this._depthCullingState.depthFunc = depthFunc;
  11495. };
  11496. Engine.prototype.setDepthFunctionToGreater = function () {
  11497. this._depthCullingState.depthFunc = this._gl.GREATER;
  11498. };
  11499. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11500. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11501. };
  11502. Engine.prototype.setDepthFunctionToLess = function () {
  11503. this._depthCullingState.depthFunc = this._gl.LESS;
  11504. };
  11505. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11506. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11507. };
  11508. Engine.prototype.getStencilBuffer = function () {
  11509. return this._stencilState.stencilTest;
  11510. };
  11511. Engine.prototype.setStencilBuffer = function (enable) {
  11512. this._stencilState.stencilTest = enable;
  11513. };
  11514. Engine.prototype.getStencilMask = function () {
  11515. return this._stencilState.stencilMask;
  11516. };
  11517. Engine.prototype.setStencilMask = function (mask) {
  11518. this._stencilState.stencilMask = mask;
  11519. };
  11520. Engine.prototype.getStencilFunction = function () {
  11521. return this._stencilState.stencilFunc;
  11522. };
  11523. Engine.prototype.getStencilFunctionReference = function () {
  11524. return this._stencilState.stencilFuncRef;
  11525. };
  11526. Engine.prototype.getStencilFunctionMask = function () {
  11527. return this._stencilState.stencilFuncMask;
  11528. };
  11529. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11530. this._stencilState.stencilFunc = stencilFunc;
  11531. };
  11532. Engine.prototype.setStencilFunctionReference = function (reference) {
  11533. this._stencilState.stencilFuncRef = reference;
  11534. };
  11535. Engine.prototype.setStencilFunctionMask = function (mask) {
  11536. this._stencilState.stencilFuncMask = mask;
  11537. };
  11538. Engine.prototype.getStencilOperationFail = function () {
  11539. return this._stencilState.stencilOpStencilFail;
  11540. };
  11541. Engine.prototype.getStencilOperationDepthFail = function () {
  11542. return this._stencilState.stencilOpDepthFail;
  11543. };
  11544. Engine.prototype.getStencilOperationPass = function () {
  11545. return this._stencilState.stencilOpStencilDepthPass;
  11546. };
  11547. Engine.prototype.setStencilOperationFail = function (operation) {
  11548. this._stencilState.stencilOpStencilFail = operation;
  11549. };
  11550. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11551. this._stencilState.stencilOpDepthFail = operation;
  11552. };
  11553. Engine.prototype.setStencilOperationPass = function (operation) {
  11554. this._stencilState.stencilOpStencilDepthPass = operation;
  11555. };
  11556. Engine.prototype.setDitheringState = function (value) {
  11557. if (value) {
  11558. this._gl.enable(this._gl.DITHER);
  11559. }
  11560. else {
  11561. this._gl.disable(this._gl.DITHER);
  11562. }
  11563. };
  11564. Engine.prototype.setRasterizerState = function (value) {
  11565. if (value) {
  11566. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11567. }
  11568. else {
  11569. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11570. }
  11571. };
  11572. /**
  11573. * stop executing a render loop function and remove it from the execution array
  11574. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11575. */
  11576. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11577. if (!renderFunction) {
  11578. this._activeRenderLoops = [];
  11579. return;
  11580. }
  11581. var index = this._activeRenderLoops.indexOf(renderFunction);
  11582. if (index >= 0) {
  11583. this._activeRenderLoops.splice(index, 1);
  11584. }
  11585. };
  11586. Engine.prototype._renderLoop = function () {
  11587. if (!this._contextWasLost) {
  11588. var shouldRender = true;
  11589. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11590. shouldRender = false;
  11591. }
  11592. if (shouldRender) {
  11593. // Start new frame
  11594. this.beginFrame();
  11595. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11596. var renderFunction = this._activeRenderLoops[index];
  11597. renderFunction();
  11598. }
  11599. // Present
  11600. this.endFrame();
  11601. }
  11602. }
  11603. if (this._activeRenderLoops.length > 0) {
  11604. // Register new frame
  11605. var requester = null;
  11606. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11607. requester = this._vrDisplay;
  11608. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11609. }
  11610. else {
  11611. this._renderingQueueLaunched = false;
  11612. }
  11613. };
  11614. /**
  11615. * Register and execute a render loop. The engine can have more than one render function.
  11616. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11617. * @example
  11618. * engine.runRenderLoop(function () {
  11619. * scene.render()
  11620. * })
  11621. */
  11622. Engine.prototype.runRenderLoop = function (renderFunction) {
  11623. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11624. return;
  11625. }
  11626. this._activeRenderLoops.push(renderFunction);
  11627. if (!this._renderingQueueLaunched) {
  11628. this._renderingQueueLaunched = true;
  11629. this._bindedRenderFunction = this._renderLoop.bind(this);
  11630. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11631. }
  11632. };
  11633. /**
  11634. * Toggle full screen mode.
  11635. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11636. * @param {any} options - an options object to be sent to the requestFullscreen function
  11637. */
  11638. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11639. if (this.isFullscreen) {
  11640. BABYLON.Tools.ExitFullscreen();
  11641. }
  11642. else {
  11643. this._pointerLockRequested = requestPointerLock;
  11644. if (this._renderingCanvas) {
  11645. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11646. }
  11647. }
  11648. };
  11649. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11650. if (stencil === void 0) { stencil = false; }
  11651. this.applyStates();
  11652. var mode = 0;
  11653. if (backBuffer && color) {
  11654. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11655. mode |= this._gl.COLOR_BUFFER_BIT;
  11656. }
  11657. if (depth) {
  11658. this._gl.clearDepth(1.0);
  11659. mode |= this._gl.DEPTH_BUFFER_BIT;
  11660. }
  11661. if (stencil) {
  11662. this._gl.clearStencil(0);
  11663. mode |= this._gl.STENCIL_BUFFER_BIT;
  11664. }
  11665. this._gl.clear(mode);
  11666. };
  11667. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11668. var gl = this._gl;
  11669. // Save state
  11670. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11671. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11672. // Change state
  11673. gl.enable(gl.SCISSOR_TEST);
  11674. gl.scissor(x, y, width, height);
  11675. // Clear
  11676. this.clear(clearColor, true, true, true);
  11677. // Restore state
  11678. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11679. if (curScissor === true) {
  11680. gl.enable(gl.SCISSOR_TEST);
  11681. }
  11682. else {
  11683. gl.disable(gl.SCISSOR_TEST);
  11684. }
  11685. };
  11686. /**
  11687. * Set the WebGL's viewport
  11688. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11689. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11690. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11691. */
  11692. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11693. var width = requiredWidth || this.getRenderWidth();
  11694. var height = requiredHeight || this.getRenderHeight();
  11695. var x = viewport.x || 0;
  11696. var y = viewport.y || 0;
  11697. this._cachedViewport = viewport;
  11698. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11699. };
  11700. /**
  11701. * Directly set the WebGL Viewport
  11702. * The x, y, width & height are directly passed to the WebGL call
  11703. * @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.
  11704. */
  11705. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11706. var currentViewport = this._cachedViewport;
  11707. this._cachedViewport = null;
  11708. this._gl.viewport(x, y, width, height);
  11709. return currentViewport;
  11710. };
  11711. Engine.prototype.beginFrame = function () {
  11712. this.onBeginFrameObservable.notifyObservers(this);
  11713. this._measureFps();
  11714. };
  11715. Engine.prototype.endFrame = function () {
  11716. //force a flush in case we are using a bad OS.
  11717. if (this._badOS) {
  11718. this.flushFramebuffer();
  11719. }
  11720. //submit frame to the vr device, if enabled
  11721. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11722. // TODO: We should only submit the frame if we read frameData successfully.
  11723. this._vrDisplay.submitFrame();
  11724. }
  11725. this.onEndFrameObservable.notifyObservers(this);
  11726. };
  11727. /**
  11728. * resize the view according to the canvas' size.
  11729. * @example
  11730. * window.addEventListener("resize", function () {
  11731. * engine.resize();
  11732. * });
  11733. */
  11734. Engine.prototype.resize = function () {
  11735. // We're not resizing the size of the canvas while in VR mode & presenting
  11736. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11737. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11738. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11739. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11740. }
  11741. };
  11742. /**
  11743. * force a specific size of the canvas
  11744. * @param {number} width - the new canvas' width
  11745. * @param {number} height - the new canvas' height
  11746. */
  11747. Engine.prototype.setSize = function (width, height) {
  11748. if (!this._renderingCanvas) {
  11749. return;
  11750. }
  11751. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11752. return;
  11753. }
  11754. this._renderingCanvas.width = width;
  11755. this._renderingCanvas.height = height;
  11756. for (var index = 0; index < this.scenes.length; index++) {
  11757. var scene = this.scenes[index];
  11758. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11759. var cam = scene.cameras[camIndex];
  11760. cam._currentRenderId = 0;
  11761. }
  11762. }
  11763. if (this.onResizeObservable.hasObservers) {
  11764. this.onResizeObservable.notifyObservers(this);
  11765. }
  11766. };
  11767. // WebVR functions
  11768. Engine.prototype.isVRDevicePresent = function () {
  11769. return !!this._vrDisplay;
  11770. };
  11771. Engine.prototype.getVRDevice = function () {
  11772. return this._vrDisplay;
  11773. };
  11774. /**
  11775. * Initializes a webVR display and starts listening to display change events.
  11776. * The onVRDisplayChangedObservable will be notified upon these changes.
  11777. * @returns The onVRDisplayChangedObservable.
  11778. */
  11779. Engine.prototype.initWebVR = function () {
  11780. this.initWebVRAsync();
  11781. return this.onVRDisplayChangedObservable;
  11782. };
  11783. /**
  11784. * Initializes a webVR display and starts listening to display change events.
  11785. * The onVRDisplayChangedObservable will be notified upon these changes.
  11786. * @returns A promise containing a VRDisplay and if vr is supported.
  11787. */
  11788. Engine.prototype.initWebVRAsync = function () {
  11789. var _this = this;
  11790. var notifyObservers = function () {
  11791. var eventArgs = {
  11792. vrDisplay: _this._vrDisplay,
  11793. vrSupported: _this._vrSupported
  11794. };
  11795. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11796. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11797. };
  11798. if (!this._onVrDisplayConnect) {
  11799. this._onVrDisplayConnect = function (event) {
  11800. _this._vrDisplay = event.display;
  11801. notifyObservers();
  11802. };
  11803. this._onVrDisplayDisconnect = function () {
  11804. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11805. _this._vrDisplay = undefined;
  11806. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11807. notifyObservers();
  11808. };
  11809. this._onVrDisplayPresentChange = function () {
  11810. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11811. };
  11812. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11813. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11814. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11815. }
  11816. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11817. this._webVRInitPromise.then(notifyObservers);
  11818. return this._webVRInitPromise;
  11819. };
  11820. Engine.prototype.enableVR = function () {
  11821. var _this = this;
  11822. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11823. var onResolved = function () {
  11824. _this.onVRRequestPresentComplete.notifyObservers(true);
  11825. _this._onVRFullScreenTriggered();
  11826. };
  11827. var onRejected = function () {
  11828. _this.onVRRequestPresentComplete.notifyObservers(false);
  11829. };
  11830. this.onVRRequestPresentStart.notifyObservers(this);
  11831. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11832. }
  11833. };
  11834. Engine.prototype.disableVR = function () {
  11835. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11836. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11837. }
  11838. };
  11839. Engine.prototype._getVRDisplaysAsync = function () {
  11840. var _this = this;
  11841. return new Promise(function (res, rej) {
  11842. if (navigator.getVRDisplays) {
  11843. navigator.getVRDisplays().then(function (devices) {
  11844. _this._vrSupported = true;
  11845. // note that devices may actually be an empty array. This is fine;
  11846. // we expect this._vrDisplay to be undefined in this case.
  11847. _this._vrDisplay = devices[0];
  11848. res({
  11849. vrDisplay: _this._vrDisplay,
  11850. vrSupported: _this._vrSupported
  11851. });
  11852. });
  11853. }
  11854. else {
  11855. _this._vrDisplay = undefined;
  11856. _this._vrSupported = false;
  11857. res({
  11858. vrDisplay: _this._vrDisplay,
  11859. vrSupported: _this._vrSupported
  11860. });
  11861. }
  11862. });
  11863. };
  11864. /**
  11865. * Binds the frame buffer to the specified texture.
  11866. * @param texture The texture to render to or null for the default canvas
  11867. * @param faceIndex The face of the texture to render to in case of cube texture
  11868. * @param requiredWidth The width of the target to render to
  11869. * @param requiredHeight The height of the target to render to
  11870. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11871. * @param depthStencilTexture The depth stencil texture to use to render
  11872. */
  11873. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11874. if (this._currentRenderTarget) {
  11875. this.unBindFramebuffer(this._currentRenderTarget);
  11876. }
  11877. this._currentRenderTarget = texture;
  11878. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11879. var gl = this._gl;
  11880. if (texture.isCube) {
  11881. if (faceIndex === undefined) {
  11882. faceIndex = 0;
  11883. }
  11884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11885. if (depthStencilTexture) {
  11886. if (depthStencilTexture._generateStencilBuffer) {
  11887. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11888. }
  11889. else {
  11890. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11891. }
  11892. }
  11893. }
  11894. if (this._cachedViewport && !forceFullscreenViewport) {
  11895. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11896. }
  11897. else {
  11898. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11899. }
  11900. this.wipeCaches();
  11901. };
  11902. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11903. if (this._currentFramebuffer !== framebuffer) {
  11904. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11905. this._currentFramebuffer = framebuffer;
  11906. }
  11907. };
  11908. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11909. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11910. this._currentRenderTarget = null;
  11911. // If MSAA, we need to bitblt back to main texture
  11912. var gl = this._gl;
  11913. if (texture._MSAAFramebuffer) {
  11914. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11915. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11916. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11917. }
  11918. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11919. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11920. gl.generateMipmap(gl.TEXTURE_2D);
  11921. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11922. }
  11923. if (onBeforeUnbind) {
  11924. if (texture._MSAAFramebuffer) {
  11925. // Bind the correct framebuffer
  11926. this.bindUnboundFramebuffer(texture._framebuffer);
  11927. }
  11928. onBeforeUnbind();
  11929. }
  11930. this.bindUnboundFramebuffer(null);
  11931. };
  11932. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11933. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11934. this._currentRenderTarget = null;
  11935. // If MSAA, we need to bitblt back to main texture
  11936. var gl = this._gl;
  11937. if (textures[0]._MSAAFramebuffer) {
  11938. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11939. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11940. var attachments = textures[0]._attachments;
  11941. if (!attachments) {
  11942. attachments = new Array(textures.length);
  11943. textures[0]._attachments = attachments;
  11944. }
  11945. for (var i = 0; i < textures.length; i++) {
  11946. var texture = textures[i];
  11947. for (var j = 0; j < attachments.length; j++) {
  11948. attachments[j] = gl.NONE;
  11949. }
  11950. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11951. gl.readBuffer(attachments[i]);
  11952. gl.drawBuffers(attachments);
  11953. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11954. }
  11955. for (var i = 0; i < attachments.length; i++) {
  11956. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11957. }
  11958. gl.drawBuffers(attachments);
  11959. }
  11960. for (var i = 0; i < textures.length; i++) {
  11961. var texture = textures[i];
  11962. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11963. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11964. gl.generateMipmap(gl.TEXTURE_2D);
  11965. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11966. }
  11967. }
  11968. if (onBeforeUnbind) {
  11969. if (textures[0]._MSAAFramebuffer) {
  11970. // Bind the correct framebuffer
  11971. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11972. }
  11973. onBeforeUnbind();
  11974. }
  11975. this.bindUnboundFramebuffer(null);
  11976. };
  11977. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11978. if (texture.generateMipMaps) {
  11979. var gl = this._gl;
  11980. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11981. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11983. }
  11984. };
  11985. Engine.prototype.flushFramebuffer = function () {
  11986. this._gl.flush();
  11987. };
  11988. Engine.prototype.restoreDefaultFramebuffer = function () {
  11989. if (this._currentRenderTarget) {
  11990. this.unBindFramebuffer(this._currentRenderTarget);
  11991. }
  11992. else {
  11993. this.bindUnboundFramebuffer(null);
  11994. }
  11995. if (this._cachedViewport) {
  11996. this.setViewport(this._cachedViewport);
  11997. }
  11998. this.wipeCaches();
  11999. };
  12000. // UBOs
  12001. Engine.prototype.createUniformBuffer = function (elements) {
  12002. var ubo = this._gl.createBuffer();
  12003. if (!ubo) {
  12004. throw new Error("Unable to create uniform buffer");
  12005. }
  12006. this.bindUniformBuffer(ubo);
  12007. if (elements instanceof Float32Array) {
  12008. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12009. }
  12010. else {
  12011. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12012. }
  12013. this.bindUniformBuffer(null);
  12014. ubo.references = 1;
  12015. return ubo;
  12016. };
  12017. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12018. var ubo = this._gl.createBuffer();
  12019. if (!ubo) {
  12020. throw new Error("Unable to create dynamic uniform buffer");
  12021. }
  12022. this.bindUniformBuffer(ubo);
  12023. if (elements instanceof Float32Array) {
  12024. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12025. }
  12026. else {
  12027. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12028. }
  12029. this.bindUniformBuffer(null);
  12030. ubo.references = 1;
  12031. return ubo;
  12032. };
  12033. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12034. this.bindUniformBuffer(uniformBuffer);
  12035. if (offset === undefined) {
  12036. offset = 0;
  12037. }
  12038. if (count === undefined) {
  12039. if (elements instanceof Float32Array) {
  12040. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12041. }
  12042. else {
  12043. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12044. }
  12045. }
  12046. else {
  12047. if (elements instanceof Float32Array) {
  12048. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12049. }
  12050. else {
  12051. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12052. }
  12053. }
  12054. this.bindUniformBuffer(null);
  12055. };
  12056. // VBOs
  12057. Engine.prototype._resetVertexBufferBinding = function () {
  12058. this.bindArrayBuffer(null);
  12059. this._cachedVertexBuffers = null;
  12060. };
  12061. Engine.prototype.createVertexBuffer = function (vertices) {
  12062. var vbo = this._gl.createBuffer();
  12063. if (!vbo) {
  12064. throw new Error("Unable to create vertex buffer");
  12065. }
  12066. this.bindArrayBuffer(vbo);
  12067. if (vertices instanceof Float32Array) {
  12068. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12069. }
  12070. else {
  12071. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12072. }
  12073. this._resetVertexBufferBinding();
  12074. vbo.references = 1;
  12075. return vbo;
  12076. };
  12077. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12078. var vbo = this._gl.createBuffer();
  12079. if (!vbo) {
  12080. throw new Error("Unable to create dynamic vertex buffer");
  12081. }
  12082. this.bindArrayBuffer(vbo);
  12083. if (vertices instanceof Float32Array) {
  12084. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12085. }
  12086. else {
  12087. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12088. }
  12089. this._resetVertexBufferBinding();
  12090. vbo.references = 1;
  12091. return vbo;
  12092. };
  12093. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12094. if (offset === void 0) { offset = 0; }
  12095. // Force cache update
  12096. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12097. this.bindIndexBuffer(indexBuffer);
  12098. var arrayBuffer;
  12099. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12100. arrayBuffer = indices;
  12101. }
  12102. else {
  12103. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12104. }
  12105. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12106. this._resetIndexBufferBinding();
  12107. };
  12108. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12109. this.bindArrayBuffer(vertexBuffer);
  12110. if (offset === undefined) {
  12111. offset = 0;
  12112. }
  12113. if (count === undefined) {
  12114. if (vertices instanceof Float32Array) {
  12115. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12116. }
  12117. else {
  12118. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12119. }
  12120. }
  12121. else {
  12122. if (vertices instanceof Float32Array) {
  12123. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12124. }
  12125. else {
  12126. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12127. }
  12128. }
  12129. this._resetVertexBufferBinding();
  12130. };
  12131. Engine.prototype._resetIndexBufferBinding = function () {
  12132. this.bindIndexBuffer(null);
  12133. this._cachedIndexBuffer = null;
  12134. };
  12135. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12136. var vbo = this._gl.createBuffer();
  12137. if (!vbo) {
  12138. throw new Error("Unable to create index buffer");
  12139. }
  12140. this.bindIndexBuffer(vbo);
  12141. // Check for 32 bits indices
  12142. var arrayBuffer;
  12143. var need32Bits = false;
  12144. if (indices instanceof Uint16Array) {
  12145. arrayBuffer = indices;
  12146. }
  12147. else {
  12148. //check 32 bit support
  12149. if (this._caps.uintIndices) {
  12150. if (indices instanceof Uint32Array) {
  12151. arrayBuffer = indices;
  12152. need32Bits = true;
  12153. }
  12154. else {
  12155. //number[] or Int32Array, check if 32 bit is necessary
  12156. for (var index = 0; index < indices.length; index++) {
  12157. if (indices[index] > 65535) {
  12158. need32Bits = true;
  12159. break;
  12160. }
  12161. }
  12162. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12163. }
  12164. }
  12165. else {
  12166. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12167. arrayBuffer = new Uint16Array(indices);
  12168. }
  12169. }
  12170. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12171. this._resetIndexBufferBinding();
  12172. vbo.references = 1;
  12173. vbo.is32Bits = need32Bits;
  12174. return vbo;
  12175. };
  12176. Engine.prototype.bindArrayBuffer = function (buffer) {
  12177. if (!this._vaoRecordInProgress) {
  12178. this._unbindVertexArrayObject();
  12179. }
  12180. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12181. };
  12182. Engine.prototype.bindUniformBuffer = function (buffer) {
  12183. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12184. };
  12185. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12186. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12187. };
  12188. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12189. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12190. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12191. };
  12192. ;
  12193. Engine.prototype.bindIndexBuffer = function (buffer) {
  12194. if (!this._vaoRecordInProgress) {
  12195. this._unbindVertexArrayObject();
  12196. }
  12197. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12198. };
  12199. Engine.prototype.bindBuffer = function (buffer, target) {
  12200. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12201. this._gl.bindBuffer(target, buffer);
  12202. this._currentBoundBuffer[target] = buffer;
  12203. }
  12204. };
  12205. Engine.prototype.updateArrayBuffer = function (data) {
  12206. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12207. };
  12208. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12209. var pointer = this._currentBufferPointers[indx];
  12210. var changed = false;
  12211. if (!pointer.active) {
  12212. changed = true;
  12213. pointer.active = true;
  12214. pointer.index = indx;
  12215. pointer.size = size;
  12216. pointer.type = type;
  12217. pointer.normalized = normalized;
  12218. pointer.stride = stride;
  12219. pointer.offset = offset;
  12220. pointer.buffer = buffer;
  12221. }
  12222. else {
  12223. if (pointer.buffer !== buffer) {
  12224. pointer.buffer = buffer;
  12225. changed = true;
  12226. }
  12227. if (pointer.size !== size) {
  12228. pointer.size = size;
  12229. changed = true;
  12230. }
  12231. if (pointer.type !== type) {
  12232. pointer.type = type;
  12233. changed = true;
  12234. }
  12235. if (pointer.normalized !== normalized) {
  12236. pointer.normalized = normalized;
  12237. changed = true;
  12238. }
  12239. if (pointer.stride !== stride) {
  12240. pointer.stride = stride;
  12241. changed = true;
  12242. }
  12243. if (pointer.offset !== offset) {
  12244. pointer.offset = offset;
  12245. changed = true;
  12246. }
  12247. }
  12248. if (changed || this._vaoRecordInProgress) {
  12249. this.bindArrayBuffer(buffer);
  12250. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12251. }
  12252. };
  12253. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12254. if (indexBuffer == null) {
  12255. return;
  12256. }
  12257. if (this._cachedIndexBuffer !== indexBuffer) {
  12258. this._cachedIndexBuffer = indexBuffer;
  12259. this.bindIndexBuffer(indexBuffer);
  12260. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12261. }
  12262. };
  12263. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12264. var attributes = effect.getAttributesNames();
  12265. if (!this._vaoRecordInProgress) {
  12266. this._unbindVertexArrayObject();
  12267. }
  12268. this.unbindAllAttributes();
  12269. for (var index = 0; index < attributes.length; index++) {
  12270. var order = effect.getAttributeLocation(index);
  12271. if (order >= 0) {
  12272. var vertexBuffer = vertexBuffers[attributes[index]];
  12273. if (!vertexBuffer) {
  12274. continue;
  12275. }
  12276. this._gl.enableVertexAttribArray(order);
  12277. if (!this._vaoRecordInProgress) {
  12278. this._vertexAttribArraysEnabled[order] = true;
  12279. }
  12280. var buffer = vertexBuffer.getBuffer();
  12281. if (buffer) {
  12282. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12283. if (vertexBuffer.getIsInstanced()) {
  12284. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12285. if (!this._vaoRecordInProgress) {
  12286. this._currentInstanceLocations.push(order);
  12287. this._currentInstanceBuffers.push(buffer);
  12288. }
  12289. }
  12290. }
  12291. }
  12292. }
  12293. };
  12294. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12295. var vao = this._gl.createVertexArray();
  12296. this._vaoRecordInProgress = true;
  12297. this._gl.bindVertexArray(vao);
  12298. this._mustWipeVertexAttributes = true;
  12299. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12300. this.bindIndexBuffer(indexBuffer);
  12301. this._vaoRecordInProgress = false;
  12302. this._gl.bindVertexArray(null);
  12303. return vao;
  12304. };
  12305. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12306. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12307. this._cachedVertexArrayObject = vertexArrayObject;
  12308. this._gl.bindVertexArray(vertexArrayObject);
  12309. this._cachedVertexBuffers = null;
  12310. this._cachedIndexBuffer = null;
  12311. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12312. this._mustWipeVertexAttributes = true;
  12313. }
  12314. };
  12315. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12316. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12317. this._cachedVertexBuffers = vertexBuffer;
  12318. this._cachedEffectForVertexBuffers = effect;
  12319. var attributesCount = effect.getAttributesCount();
  12320. this._unbindVertexArrayObject();
  12321. this.unbindAllAttributes();
  12322. var offset = 0;
  12323. for (var index = 0; index < attributesCount; index++) {
  12324. if (index < vertexDeclaration.length) {
  12325. var order = effect.getAttributeLocation(index);
  12326. if (order >= 0) {
  12327. this._gl.enableVertexAttribArray(order);
  12328. this._vertexAttribArraysEnabled[order] = true;
  12329. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12330. }
  12331. offset += vertexDeclaration[index] * 4;
  12332. }
  12333. }
  12334. }
  12335. this._bindIndexBufferWithCache(indexBuffer);
  12336. };
  12337. Engine.prototype._unbindVertexArrayObject = function () {
  12338. if (!this._cachedVertexArrayObject) {
  12339. return;
  12340. }
  12341. this._cachedVertexArrayObject = null;
  12342. this._gl.bindVertexArray(null);
  12343. };
  12344. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12345. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12346. this._cachedVertexBuffers = vertexBuffers;
  12347. this._cachedEffectForVertexBuffers = effect;
  12348. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12349. }
  12350. this._bindIndexBufferWithCache(indexBuffer);
  12351. };
  12352. Engine.prototype.unbindInstanceAttributes = function () {
  12353. var boundBuffer;
  12354. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12355. var instancesBuffer = this._currentInstanceBuffers[i];
  12356. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12357. boundBuffer = instancesBuffer;
  12358. this.bindArrayBuffer(instancesBuffer);
  12359. }
  12360. var offsetLocation = this._currentInstanceLocations[i];
  12361. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12362. }
  12363. this._currentInstanceBuffers.length = 0;
  12364. this._currentInstanceLocations.length = 0;
  12365. };
  12366. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12367. this._gl.deleteVertexArray(vao);
  12368. };
  12369. Engine.prototype._releaseBuffer = function (buffer) {
  12370. buffer.references--;
  12371. if (buffer.references === 0) {
  12372. this._gl.deleteBuffer(buffer);
  12373. return true;
  12374. }
  12375. return false;
  12376. };
  12377. Engine.prototype.createInstancesBuffer = function (capacity) {
  12378. var buffer = this._gl.createBuffer();
  12379. if (!buffer) {
  12380. throw new Error("Unable to create instance buffer");
  12381. }
  12382. buffer.capacity = capacity;
  12383. this.bindArrayBuffer(buffer);
  12384. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12385. return buffer;
  12386. };
  12387. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12388. this._gl.deleteBuffer(buffer);
  12389. };
  12390. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12391. this.bindArrayBuffer(instancesBuffer);
  12392. if (data) {
  12393. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12394. }
  12395. if (offsetLocations[0].index !== undefined) {
  12396. var stride = 0;
  12397. for (var i = 0; i < offsetLocations.length; i++) {
  12398. var ai = offsetLocations[i];
  12399. stride += ai.attributeSize * 4;
  12400. }
  12401. for (var i = 0; i < offsetLocations.length; i++) {
  12402. var ai = offsetLocations[i];
  12403. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12404. this._gl.enableVertexAttribArray(ai.index);
  12405. this._vertexAttribArraysEnabled[ai.index] = true;
  12406. }
  12407. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12408. this._gl.vertexAttribDivisor(ai.index, 1);
  12409. this._currentInstanceLocations.push(ai.index);
  12410. this._currentInstanceBuffers.push(instancesBuffer);
  12411. }
  12412. }
  12413. else {
  12414. for (var index = 0; index < 4; index++) {
  12415. var offsetLocation = offsetLocations[index];
  12416. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12417. this._gl.enableVertexAttribArray(offsetLocation);
  12418. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12419. }
  12420. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12421. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12422. this._currentInstanceLocations.push(offsetLocation);
  12423. this._currentInstanceBuffers.push(instancesBuffer);
  12424. }
  12425. }
  12426. };
  12427. Engine.prototype.applyStates = function () {
  12428. this._depthCullingState.apply(this._gl);
  12429. this._stencilState.apply(this._gl);
  12430. this._alphaState.apply(this._gl);
  12431. };
  12432. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12433. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12434. };
  12435. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12436. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12437. };
  12438. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12439. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12440. };
  12441. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12442. // Apply states
  12443. this.applyStates();
  12444. this._drawCalls.addCount(1, false);
  12445. // Render
  12446. var drawMode = this.DrawMode(fillMode);
  12447. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12448. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12449. if (instancesCount) {
  12450. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12451. }
  12452. else {
  12453. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12454. }
  12455. };
  12456. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12457. // Apply states
  12458. this.applyStates();
  12459. this._drawCalls.addCount(1, false);
  12460. var drawMode = this.DrawMode(fillMode);
  12461. if (instancesCount) {
  12462. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12463. }
  12464. else {
  12465. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12466. }
  12467. };
  12468. Engine.prototype.DrawMode = function (fillMode) {
  12469. switch (fillMode) {
  12470. // Triangle views
  12471. case BABYLON.Material.TriangleFillMode:
  12472. return this._gl.TRIANGLES;
  12473. case BABYLON.Material.PointFillMode:
  12474. return this._gl.POINTS;
  12475. case BABYLON.Material.WireFrameFillMode:
  12476. return this._gl.LINES;
  12477. // Draw modes
  12478. case BABYLON.Material.PointListDrawMode:
  12479. return this._gl.POINTS;
  12480. case BABYLON.Material.LineListDrawMode:
  12481. return this._gl.LINES;
  12482. case BABYLON.Material.LineLoopDrawMode:
  12483. return this._gl.LINE_LOOP;
  12484. case BABYLON.Material.LineStripDrawMode:
  12485. return this._gl.LINE_STRIP;
  12486. case BABYLON.Material.TriangleStripDrawMode:
  12487. return this._gl.TRIANGLE_STRIP;
  12488. case BABYLON.Material.TriangleFanDrawMode:
  12489. return this._gl.TRIANGLE_FAN;
  12490. default:
  12491. return this._gl.TRIANGLES;
  12492. }
  12493. };
  12494. // Shaders
  12495. Engine.prototype._releaseEffect = function (effect) {
  12496. if (this._compiledEffects[effect._key]) {
  12497. delete this._compiledEffects[effect._key];
  12498. this._deleteProgram(effect.getProgram());
  12499. }
  12500. };
  12501. Engine.prototype._deleteProgram = function (program) {
  12502. if (program) {
  12503. program.__SPECTOR_rebuildProgram = null;
  12504. if (program.transformFeedback) {
  12505. this.deleteTransformFeedback(program.transformFeedback);
  12506. program.transformFeedback = null;
  12507. }
  12508. this._gl.deleteProgram(program);
  12509. }
  12510. };
  12511. /**
  12512. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12513. * @param samplers An array of string used to represent textures
  12514. */
  12515. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12516. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12517. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12518. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12519. if (this._compiledEffects[name]) {
  12520. var compiledEffect = this._compiledEffects[name];
  12521. if (onCompiled && compiledEffect.isReady()) {
  12522. onCompiled(compiledEffect);
  12523. }
  12524. return compiledEffect;
  12525. }
  12526. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12527. effect._key = name;
  12528. this._compiledEffects[name] = effect;
  12529. return effect;
  12530. };
  12531. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12532. if (uniformsNames === void 0) { uniformsNames = []; }
  12533. if (samplers === void 0) { samplers = []; }
  12534. if (defines === void 0) { defines = ""; }
  12535. return this.createEffect({
  12536. vertex: "particles",
  12537. fragmentElement: fragmentName
  12538. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12539. };
  12540. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12541. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12542. context = context || this._gl;
  12543. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12544. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12545. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12546. };
  12547. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12548. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12549. context = context || this._gl;
  12550. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12551. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12552. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12553. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12554. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12555. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12556. return program;
  12557. };
  12558. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12559. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12560. var shaderProgram = context.createProgram();
  12561. if (!shaderProgram) {
  12562. throw new Error("Unable to create program");
  12563. }
  12564. context.attachShader(shaderProgram, vertexShader);
  12565. context.attachShader(shaderProgram, fragmentShader);
  12566. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12567. var transformFeedback = this.createTransformFeedback();
  12568. this.bindTransformFeedback(transformFeedback);
  12569. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12570. shaderProgram.transformFeedback = transformFeedback;
  12571. }
  12572. context.linkProgram(shaderProgram);
  12573. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12574. this.bindTransformFeedback(null);
  12575. }
  12576. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12577. if (!linked) {
  12578. context.validateProgram(shaderProgram);
  12579. var error = context.getProgramInfoLog(shaderProgram);
  12580. if (error) {
  12581. throw new Error(error);
  12582. }
  12583. }
  12584. context.deleteShader(vertexShader);
  12585. context.deleteShader(fragmentShader);
  12586. return shaderProgram;
  12587. };
  12588. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12589. var results = new Array();
  12590. for (var index = 0; index < uniformsNames.length; index++) {
  12591. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12592. }
  12593. return results;
  12594. };
  12595. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12596. var results = [];
  12597. for (var index = 0; index < attributesNames.length; index++) {
  12598. try {
  12599. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12600. }
  12601. catch (e) {
  12602. results.push(-1);
  12603. }
  12604. }
  12605. return results;
  12606. };
  12607. Engine.prototype.enableEffect = function (effect) {
  12608. if (!effect) {
  12609. return;
  12610. }
  12611. // Use program
  12612. this.bindSamplers(effect);
  12613. this._currentEffect = effect;
  12614. if (effect.onBind) {
  12615. effect.onBind(effect);
  12616. }
  12617. effect.onBindObservable.notifyObservers(effect);
  12618. };
  12619. Engine.prototype.setIntArray = function (uniform, array) {
  12620. if (!uniform)
  12621. return;
  12622. this._gl.uniform1iv(uniform, array);
  12623. };
  12624. Engine.prototype.setIntArray2 = function (uniform, array) {
  12625. if (!uniform || array.length % 2 !== 0)
  12626. return;
  12627. this._gl.uniform2iv(uniform, array);
  12628. };
  12629. Engine.prototype.setIntArray3 = function (uniform, array) {
  12630. if (!uniform || array.length % 3 !== 0)
  12631. return;
  12632. this._gl.uniform3iv(uniform, array);
  12633. };
  12634. Engine.prototype.setIntArray4 = function (uniform, array) {
  12635. if (!uniform || array.length % 4 !== 0)
  12636. return;
  12637. this._gl.uniform4iv(uniform, array);
  12638. };
  12639. Engine.prototype.setFloatArray = function (uniform, array) {
  12640. if (!uniform)
  12641. return;
  12642. this._gl.uniform1fv(uniform, array);
  12643. };
  12644. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12645. if (!uniform || array.length % 2 !== 0)
  12646. return;
  12647. this._gl.uniform2fv(uniform, array);
  12648. };
  12649. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12650. if (!uniform || array.length % 3 !== 0)
  12651. return;
  12652. this._gl.uniform3fv(uniform, array);
  12653. };
  12654. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12655. if (!uniform || array.length % 4 !== 0)
  12656. return;
  12657. this._gl.uniform4fv(uniform, array);
  12658. };
  12659. Engine.prototype.setArray = function (uniform, array) {
  12660. if (!uniform)
  12661. return;
  12662. this._gl.uniform1fv(uniform, array);
  12663. };
  12664. Engine.prototype.setArray2 = function (uniform, array) {
  12665. if (!uniform || array.length % 2 !== 0)
  12666. return;
  12667. this._gl.uniform2fv(uniform, array);
  12668. };
  12669. Engine.prototype.setArray3 = function (uniform, array) {
  12670. if (!uniform || array.length % 3 !== 0)
  12671. return;
  12672. this._gl.uniform3fv(uniform, array);
  12673. };
  12674. Engine.prototype.setArray4 = function (uniform, array) {
  12675. if (!uniform || array.length % 4 !== 0)
  12676. return;
  12677. this._gl.uniform4fv(uniform, array);
  12678. };
  12679. Engine.prototype.setMatrices = function (uniform, matrices) {
  12680. if (!uniform)
  12681. return;
  12682. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12683. };
  12684. Engine.prototype.setMatrix = function (uniform, matrix) {
  12685. if (!uniform)
  12686. return;
  12687. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12688. };
  12689. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12690. if (!uniform)
  12691. return;
  12692. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12693. };
  12694. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12695. if (!uniform)
  12696. return;
  12697. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12698. };
  12699. Engine.prototype.setInt = function (uniform, value) {
  12700. if (!uniform)
  12701. return;
  12702. this._gl.uniform1i(uniform, value);
  12703. };
  12704. Engine.prototype.setFloat = function (uniform, value) {
  12705. if (!uniform)
  12706. return;
  12707. this._gl.uniform1f(uniform, value);
  12708. };
  12709. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12710. if (!uniform)
  12711. return;
  12712. this._gl.uniform2f(uniform, x, y);
  12713. };
  12714. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12715. if (!uniform)
  12716. return;
  12717. this._gl.uniform3f(uniform, x, y, z);
  12718. };
  12719. Engine.prototype.setBool = function (uniform, bool) {
  12720. if (!uniform)
  12721. return;
  12722. this._gl.uniform1i(uniform, bool);
  12723. };
  12724. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12725. if (!uniform)
  12726. return;
  12727. this._gl.uniform4f(uniform, x, y, z, w);
  12728. };
  12729. Engine.prototype.setColor3 = function (uniform, color3) {
  12730. if (!uniform)
  12731. return;
  12732. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12733. };
  12734. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12735. if (!uniform)
  12736. return;
  12737. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12738. };
  12739. /**
  12740. * Sets a Color4 on a uniform variable
  12741. * @param uniform defines the uniform location
  12742. * @param color4 defines the value to be set
  12743. */
  12744. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12745. if (!uniform)
  12746. return;
  12747. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12748. };
  12749. // States
  12750. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12751. if (zOffset === void 0) { zOffset = 0; }
  12752. if (reverseSide === void 0) { reverseSide = false; }
  12753. // Culling
  12754. if (this._depthCullingState.cull !== culling || force) {
  12755. this._depthCullingState.cull = culling;
  12756. }
  12757. // Cull face
  12758. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12759. if (this._depthCullingState.cullFace !== cullFace || force) {
  12760. this._depthCullingState.cullFace = cullFace;
  12761. }
  12762. // Z offset
  12763. this.setZOffset(zOffset);
  12764. // Front face
  12765. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12766. if (this._depthCullingState.frontFace !== frontFace || force) {
  12767. this._depthCullingState.frontFace = frontFace;
  12768. }
  12769. };
  12770. Engine.prototype.setZOffset = function (value) {
  12771. this._depthCullingState.zOffset = value;
  12772. };
  12773. Engine.prototype.getZOffset = function () {
  12774. return this._depthCullingState.zOffset;
  12775. };
  12776. Engine.prototype.setDepthBuffer = function (enable) {
  12777. this._depthCullingState.depthTest = enable;
  12778. };
  12779. Engine.prototype.getDepthWrite = function () {
  12780. return this._depthCullingState.depthMask;
  12781. };
  12782. Engine.prototype.setDepthWrite = function (enable) {
  12783. this._depthCullingState.depthMask = enable;
  12784. };
  12785. Engine.prototype.setColorWrite = function (enable) {
  12786. this._gl.colorMask(enable, enable, enable, enable);
  12787. this._colorWrite = enable;
  12788. };
  12789. Engine.prototype.getColorWrite = function () {
  12790. return this._colorWrite;
  12791. };
  12792. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12793. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12794. };
  12795. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12796. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12797. if (this._alphaMode === mode) {
  12798. return;
  12799. }
  12800. switch (mode) {
  12801. case Engine.ALPHA_DISABLE:
  12802. this._alphaState.alphaBlend = false;
  12803. break;
  12804. case Engine.ALPHA_PREMULTIPLIED:
  12805. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12806. this._alphaState.alphaBlend = true;
  12807. break;
  12808. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12809. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12810. this._alphaState.alphaBlend = true;
  12811. break;
  12812. case Engine.ALPHA_COMBINE:
  12813. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12814. this._alphaState.alphaBlend = true;
  12815. break;
  12816. case Engine.ALPHA_ONEONE:
  12817. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12818. this._alphaState.alphaBlend = true;
  12819. break;
  12820. case Engine.ALPHA_ADD:
  12821. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12822. this._alphaState.alphaBlend = true;
  12823. break;
  12824. case Engine.ALPHA_SUBTRACT:
  12825. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12826. this._alphaState.alphaBlend = true;
  12827. break;
  12828. case Engine.ALPHA_MULTIPLY:
  12829. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12830. this._alphaState.alphaBlend = true;
  12831. break;
  12832. case Engine.ALPHA_MAXIMIZED:
  12833. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12834. this._alphaState.alphaBlend = true;
  12835. break;
  12836. case Engine.ALPHA_INTERPOLATE:
  12837. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12838. this._alphaState.alphaBlend = true;
  12839. break;
  12840. case Engine.ALPHA_SCREENMODE:
  12841. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12842. this._alphaState.alphaBlend = true;
  12843. break;
  12844. }
  12845. if (!noDepthWriteChange) {
  12846. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12847. }
  12848. this._alphaMode = mode;
  12849. };
  12850. Engine.prototype.getAlphaMode = function () {
  12851. return this._alphaMode;
  12852. };
  12853. // Textures
  12854. Engine.prototype.wipeCaches = function (bruteForce) {
  12855. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12856. return;
  12857. }
  12858. this._currentEffect = null;
  12859. // 6/8/2017: deltakosh: Should not be required anymore.
  12860. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12861. if (bruteForce) {
  12862. this.resetTextureCache();
  12863. this._currentProgram = null;
  12864. this._stencilState.reset();
  12865. this._depthCullingState.reset();
  12866. this.setDepthFunctionToLessOrEqual();
  12867. this._alphaState.reset();
  12868. }
  12869. this._resetVertexBufferBinding();
  12870. this._cachedIndexBuffer = null;
  12871. this._cachedEffectForVertexBuffers = null;
  12872. this._unbindVertexArrayObject();
  12873. this.bindIndexBuffer(null);
  12874. };
  12875. /**
  12876. * Set the compressed texture format to use, based on the formats you have, and the formats
  12877. * supported by the hardware / browser.
  12878. *
  12879. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12880. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12881. * to API arguments needed to compressed textures. This puts the burden on the container
  12882. * generator to house the arcane code for determining these for current & future formats.
  12883. *
  12884. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12885. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12886. *
  12887. * Note: The result of this call is not taken into account when a texture is base64.
  12888. *
  12889. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12890. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12891. *
  12892. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12893. * @returns The extension selected.
  12894. */
  12895. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12896. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12897. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12898. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12899. return this._textureFormatInUse = this._texturesSupported[i];
  12900. }
  12901. }
  12902. }
  12903. // actively set format to nothing, to allow this to be called more than once
  12904. // and possibly fail the 2nd time
  12905. this._textureFormatInUse = null;
  12906. return null;
  12907. };
  12908. Engine.prototype._createTexture = function () {
  12909. var texture = this._gl.createTexture();
  12910. if (!texture) {
  12911. throw new Error("Unable to create texture");
  12912. }
  12913. return texture;
  12914. };
  12915. /**
  12916. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12917. * @param {string} urlArg- This contains one of the following:
  12918. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12919. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12920. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12921. *
  12922. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12923. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12924. * @param {Scene} scene- Needed for loading to the correct scene.
  12925. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12926. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12927. * @param {callback} onError- Optional callback to be called upon failure.
  12928. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12929. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12930. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12931. *
  12932. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12933. */
  12934. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12935. var _this = this;
  12936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12937. if (onLoad === void 0) { onLoad = null; }
  12938. if (onError === void 0) { onError = null; }
  12939. if (buffer === void 0) { buffer = null; }
  12940. if (fallBack === void 0) { fallBack = null; }
  12941. if (format === void 0) { format = null; }
  12942. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12943. var fromData = url.substr(0, 5) === "data:";
  12944. var fromBlob = url.substr(0, 5) === "blob:";
  12945. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12946. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12947. // establish the file extension, if possible
  12948. var lastDot = url.lastIndexOf('.');
  12949. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12950. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12951. var isTGA = (extension.indexOf(".tga") === 0);
  12952. // determine if a ktx file should be substituted
  12953. var isKTX = false;
  12954. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12955. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12956. isKTX = true;
  12957. }
  12958. if (scene) {
  12959. scene._addPendingData(texture);
  12960. }
  12961. texture.url = url;
  12962. texture.generateMipMaps = !noMipmap;
  12963. texture.samplingMode = samplingMode;
  12964. texture.invertY = invertY;
  12965. if (!this._doNotHandleContextLost) {
  12966. // Keep a link to the buffer only if we plan to handle context lost
  12967. texture._buffer = buffer;
  12968. }
  12969. var onLoadObserver = null;
  12970. if (onLoad && !fallBack) {
  12971. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12972. }
  12973. if (!fallBack)
  12974. this._internalTexturesCache.push(texture);
  12975. var onerror = function (message, exception) {
  12976. if (scene) {
  12977. scene._removePendingData(texture);
  12978. }
  12979. if (onLoadObserver) {
  12980. texture.onLoadedObservable.remove(onLoadObserver);
  12981. }
  12982. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12983. if (isKTX) {
  12984. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12985. }
  12986. else if (BABYLON.Tools.UseFallbackTexture) {
  12987. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12988. }
  12989. if (onError) {
  12990. onError(message || "Unknown error", exception);
  12991. }
  12992. };
  12993. var callback = null;
  12994. // processing for non-image formats
  12995. if (isKTX || isTGA || isDDS) {
  12996. if (isKTX) {
  12997. callback = function (data) {
  12998. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12999. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13000. ktx.uploadLevels(_this._gl, !noMipmap);
  13001. return false;
  13002. }, samplingMode);
  13003. };
  13004. }
  13005. else if (isTGA) {
  13006. callback = function (arrayBuffer) {
  13007. var data = new Uint8Array(arrayBuffer);
  13008. var header = BABYLON.TGATools.GetTGAHeader(data);
  13009. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13010. BABYLON.TGATools.UploadContent(_this._gl, data);
  13011. return false;
  13012. }, samplingMode);
  13013. };
  13014. }
  13015. else if (isDDS) {
  13016. callback = function (data) {
  13017. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13018. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13019. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13020. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13021. return false;
  13022. }, samplingMode);
  13023. };
  13024. }
  13025. if (!buffer) {
  13026. this._loadFile(url, function (data) {
  13027. if (callback) {
  13028. callback(data);
  13029. }
  13030. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13031. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13032. });
  13033. }
  13034. else {
  13035. if (callback) {
  13036. callback(buffer);
  13037. }
  13038. }
  13039. // image format processing
  13040. }
  13041. else {
  13042. var onload = function (img) {
  13043. if (fromBlob && !_this._doNotHandleContextLost) {
  13044. // We need to store the image if we need to rebuild the texture
  13045. // in case of a webgl context lost
  13046. texture._buffer = img;
  13047. }
  13048. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13049. var gl = _this._gl;
  13050. var isPot = (img.width === potWidth && img.height === potHeight);
  13051. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13052. if (isPot) {
  13053. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13054. return false;
  13055. }
  13056. // Using shaders to rescale because canvas.drawImage is lossy
  13057. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13058. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13059. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13064. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13065. _this._releaseTexture(source);
  13066. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13067. continuationCallback();
  13068. });
  13069. return true;
  13070. }, samplingMode);
  13071. };
  13072. if (!fromData || isBase64)
  13073. if (buffer instanceof HTMLImageElement) {
  13074. onload(buffer);
  13075. }
  13076. else {
  13077. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13078. }
  13079. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13080. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13081. else
  13082. onload(buffer);
  13083. }
  13084. return texture;
  13085. };
  13086. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13087. var _this = this;
  13088. var rtt = this.createRenderTargetTexture({
  13089. width: destination.width,
  13090. height: destination.height,
  13091. }, {
  13092. generateMipMaps: false,
  13093. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13094. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13095. generateDepthBuffer: false,
  13096. generateStencilBuffer: false
  13097. });
  13098. if (!this._rescalePostProcess) {
  13099. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13100. }
  13101. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13102. _this._rescalePostProcess.onApply = function (effect) {
  13103. effect._bindTexture("textureSampler", source);
  13104. };
  13105. var hostingScene = scene;
  13106. if (!hostingScene) {
  13107. hostingScene = _this.scenes[_this.scenes.length - 1];
  13108. }
  13109. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13110. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13111. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13112. _this.unBindFramebuffer(rtt);
  13113. _this._releaseTexture(rtt);
  13114. if (onComplete) {
  13115. onComplete();
  13116. }
  13117. });
  13118. };
  13119. Engine.prototype._getInternalFormat = function (format) {
  13120. var internalFormat = this._gl.RGBA;
  13121. switch (format) {
  13122. case Engine.TEXTUREFORMAT_ALPHA:
  13123. internalFormat = this._gl.ALPHA;
  13124. break;
  13125. case Engine.TEXTUREFORMAT_LUMINANCE:
  13126. internalFormat = this._gl.LUMINANCE;
  13127. break;
  13128. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13129. internalFormat = this._gl.LUMINANCE_ALPHA;
  13130. break;
  13131. case Engine.TEXTUREFORMAT_RGB:
  13132. case Engine.TEXTUREFORMAT_RGB32F:
  13133. internalFormat = this._gl.RGB;
  13134. break;
  13135. case Engine.TEXTUREFORMAT_RGBA:
  13136. case Engine.TEXTUREFORMAT_RGBA32F:
  13137. internalFormat = this._gl.RGBA;
  13138. break;
  13139. case Engine.TEXTUREFORMAT_R32F:
  13140. internalFormat = this._gl.RED;
  13141. break;
  13142. case Engine.TEXTUREFORMAT_RG32F:
  13143. internalFormat = this._gl.RG;
  13144. break;
  13145. }
  13146. return internalFormat;
  13147. };
  13148. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13149. if (compression === void 0) { compression = null; }
  13150. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13151. if (!texture) {
  13152. return;
  13153. }
  13154. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13155. var internalFormat = this._getInternalFormat(format);
  13156. var textureType = this._getWebGLTextureType(type);
  13157. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13158. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13159. if (!this._doNotHandleContextLost) {
  13160. texture._bufferView = data;
  13161. texture.format = format;
  13162. texture.type = type;
  13163. texture.invertY = invertY;
  13164. texture._compression = compression;
  13165. }
  13166. if (texture.width % 4 !== 0) {
  13167. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13168. }
  13169. if (compression && data) {
  13170. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13171. }
  13172. else {
  13173. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13174. }
  13175. if (texture.generateMipMaps) {
  13176. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13177. }
  13178. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13179. // this.resetTextureCache();
  13180. texture.isReady = true;
  13181. };
  13182. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13183. if (compression === void 0) { compression = null; }
  13184. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13185. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13186. texture.baseWidth = width;
  13187. texture.baseHeight = height;
  13188. texture.width = width;
  13189. texture.height = height;
  13190. texture.format = format;
  13191. texture.generateMipMaps = generateMipMaps;
  13192. texture.samplingMode = samplingMode;
  13193. texture.invertY = invertY;
  13194. texture._compression = compression;
  13195. texture.type = type;
  13196. if (!this._doNotHandleContextLost) {
  13197. texture._bufferView = data;
  13198. }
  13199. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13200. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13201. // Filters
  13202. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13205. if (generateMipMaps) {
  13206. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13207. }
  13208. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13209. this._internalTexturesCache.push(texture);
  13210. return texture;
  13211. };
  13212. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13213. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13214. texture.baseWidth = width;
  13215. texture.baseHeight = height;
  13216. if (generateMipMaps) {
  13217. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13218. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13219. }
  13220. // this.resetTextureCache();
  13221. texture.width = width;
  13222. texture.height = height;
  13223. texture.isReady = false;
  13224. texture.generateMipMaps = generateMipMaps;
  13225. texture.samplingMode = samplingMode;
  13226. this.updateTextureSamplingMode(samplingMode, texture);
  13227. this._internalTexturesCache.push(texture);
  13228. return texture;
  13229. };
  13230. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13231. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13232. if (texture.isCube) {
  13233. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13234. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13235. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13236. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13237. }
  13238. else if (texture.is3D) {
  13239. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13240. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13241. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13242. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13243. }
  13244. else {
  13245. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13246. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13248. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13249. }
  13250. texture.samplingMode = samplingMode;
  13251. };
  13252. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13253. if (premulAlpha === void 0) { premulAlpha = false; }
  13254. if (!texture) {
  13255. return;
  13256. }
  13257. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13258. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13259. if (premulAlpha) {
  13260. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13261. }
  13262. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13263. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13264. if (texture.generateMipMaps) {
  13265. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13266. }
  13267. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13268. if (premulAlpha) {
  13269. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13270. }
  13271. texture.isReady = true;
  13272. };
  13273. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13274. if (!texture || texture._isDisabled) {
  13275. return;
  13276. }
  13277. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13278. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13279. try {
  13280. // Testing video texture support
  13281. if (this._videoTextureSupported === undefined) {
  13282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13283. if (this._gl.getError() !== 0) {
  13284. this._videoTextureSupported = false;
  13285. }
  13286. else {
  13287. this._videoTextureSupported = true;
  13288. }
  13289. }
  13290. // Copy video through the current working canvas if video texture is not supported
  13291. if (!this._videoTextureSupported) {
  13292. if (!texture._workingCanvas) {
  13293. texture._workingCanvas = document.createElement("canvas");
  13294. var context = texture._workingCanvas.getContext("2d");
  13295. if (!context) {
  13296. throw new Error("Unable to get 2d context");
  13297. }
  13298. texture._workingContext = context;
  13299. texture._workingCanvas.width = texture.width;
  13300. texture._workingCanvas.height = texture.height;
  13301. }
  13302. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13303. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13304. }
  13305. else {
  13306. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13307. }
  13308. if (texture.generateMipMaps) {
  13309. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13310. }
  13311. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13312. // this.resetTextureCache();
  13313. texture.isReady = true;
  13314. }
  13315. catch (ex) {
  13316. // Something unexpected
  13317. // Let's disable the texture
  13318. texture._isDisabled = true;
  13319. }
  13320. };
  13321. /**
  13322. * Updates a depth texture Comparison Mode and Function.
  13323. * If the comparison Function is equal to 0, the mode will be set to none.
  13324. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13325. * @param texture The texture to set the comparison function for
  13326. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13327. */
  13328. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13329. if (this.webGLVersion === 1) {
  13330. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13331. return;
  13332. }
  13333. var gl = this._gl;
  13334. if (texture.isCube) {
  13335. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13336. if (comparisonFunction === 0) {
  13337. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13339. }
  13340. else {
  13341. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13342. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13343. }
  13344. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13345. }
  13346. else {
  13347. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13348. if (comparisonFunction === 0) {
  13349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13351. }
  13352. else {
  13353. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13355. }
  13356. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13357. }
  13358. texture._comparisonFunction = comparisonFunction;
  13359. };
  13360. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13361. var width = size.width || size;
  13362. var height = size.height || size;
  13363. internalTexture.baseWidth = width;
  13364. internalTexture.baseHeight = height;
  13365. internalTexture.width = width;
  13366. internalTexture.height = height;
  13367. internalTexture.isReady = true;
  13368. internalTexture.samples = 1;
  13369. internalTexture.generateMipMaps = false;
  13370. internalTexture._generateDepthBuffer = true;
  13371. internalTexture._generateStencilBuffer = generateStencil;
  13372. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13373. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13374. internalTexture._comparisonFunction = comparisonFunction;
  13375. var gl = this._gl;
  13376. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13377. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13378. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13379. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13380. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13381. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13382. if (comparisonFunction === 0) {
  13383. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13384. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13385. }
  13386. else {
  13387. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13388. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13389. }
  13390. };
  13391. /**
  13392. * Creates a depth stencil texture.
  13393. * This is only available in WebGL 2 or with the depth texture extension available.
  13394. * @param size The size of face edge in the texture.
  13395. * @param options The options defining the texture.
  13396. * @returns The texture
  13397. */
  13398. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13399. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13400. if (!this._caps.depthTextureExtension) {
  13401. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13402. return internalTexture;
  13403. }
  13404. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13405. var gl = this._gl;
  13406. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13407. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13408. if (this.webGLVersion > 1) {
  13409. if (internalOptions.generateStencil) {
  13410. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13411. }
  13412. else {
  13413. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13414. }
  13415. }
  13416. else {
  13417. if (internalOptions.generateStencil) {
  13418. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13419. }
  13420. else {
  13421. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13422. }
  13423. }
  13424. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13425. return internalTexture;
  13426. };
  13427. /**
  13428. * Creates a depth stencil cube texture.
  13429. * This is only available in WebGL 2.
  13430. * @param size The size of face edge in the cube texture.
  13431. * @param options The options defining the cube texture.
  13432. * @returns The cube texture
  13433. */
  13434. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13435. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13436. internalTexture.isCube = true;
  13437. if (this.webGLVersion === 1) {
  13438. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13439. return internalTexture;
  13440. }
  13441. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13442. var gl = this._gl;
  13443. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13444. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13445. // Create the depth/stencil buffer
  13446. for (var face = 0; face < 6; face++) {
  13447. if (internalOptions.generateStencil) {
  13448. 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);
  13449. }
  13450. else {
  13451. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13452. }
  13453. }
  13454. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13455. return internalTexture;
  13456. };
  13457. /**
  13458. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13459. * @param renderTarget The render target to set the frame buffer for
  13460. */
  13461. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13462. // Create the framebuffer
  13463. var internalTexture = renderTarget.getInternalTexture();
  13464. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13465. return;
  13466. }
  13467. var gl = this._gl;
  13468. var depthStencilTexture = renderTarget.depthStencilTexture;
  13469. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13470. if (depthStencilTexture.isCube) {
  13471. if (depthStencilTexture._generateStencilBuffer) {
  13472. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13473. }
  13474. else {
  13475. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13476. }
  13477. }
  13478. else {
  13479. if (depthStencilTexture._generateStencilBuffer) {
  13480. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13481. }
  13482. else {
  13483. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13484. }
  13485. }
  13486. this.bindUnboundFramebuffer(null);
  13487. };
  13488. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13489. var fullOptions = new RenderTargetCreationOptions();
  13490. if (options !== undefined && typeof options === "object") {
  13491. fullOptions.generateMipMaps = options.generateMipMaps;
  13492. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13493. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13494. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13495. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13496. }
  13497. else {
  13498. fullOptions.generateMipMaps = options;
  13499. fullOptions.generateDepthBuffer = true;
  13500. fullOptions.generateStencilBuffer = false;
  13501. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13502. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13503. }
  13504. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13505. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13506. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13507. }
  13508. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13509. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13510. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13511. }
  13512. var gl = this._gl;
  13513. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13514. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13515. var width = size.width || size;
  13516. var height = size.height || size;
  13517. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13518. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13519. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13520. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13521. }
  13522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13526. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13527. // Create the framebuffer
  13528. var framebuffer = gl.createFramebuffer();
  13529. this.bindUnboundFramebuffer(framebuffer);
  13530. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13531. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13532. if (fullOptions.generateMipMaps) {
  13533. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13534. }
  13535. // Unbind
  13536. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13537. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13538. this.bindUnboundFramebuffer(null);
  13539. texture._framebuffer = framebuffer;
  13540. texture.baseWidth = width;
  13541. texture.baseHeight = height;
  13542. texture.width = width;
  13543. texture.height = height;
  13544. texture.isReady = true;
  13545. texture.samples = 1;
  13546. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13547. texture.samplingMode = fullOptions.samplingMode;
  13548. texture.type = fullOptions.type;
  13549. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13550. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13551. // this.resetTextureCache();
  13552. this._internalTexturesCache.push(texture);
  13553. return texture;
  13554. };
  13555. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13556. var generateMipMaps = false;
  13557. var generateDepthBuffer = true;
  13558. var generateStencilBuffer = false;
  13559. var generateDepthTexture = false;
  13560. var textureCount = 1;
  13561. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13562. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13563. var types = [], samplingModes = [];
  13564. if (options !== undefined) {
  13565. generateMipMaps = options.generateMipMaps;
  13566. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13567. generateStencilBuffer = options.generateStencilBuffer;
  13568. generateDepthTexture = options.generateDepthTexture;
  13569. textureCount = options.textureCount || 1;
  13570. if (options.types) {
  13571. types = options.types;
  13572. }
  13573. if (options.samplingModes) {
  13574. samplingModes = options.samplingModes;
  13575. }
  13576. }
  13577. var gl = this._gl;
  13578. // Create the framebuffer
  13579. var framebuffer = gl.createFramebuffer();
  13580. this.bindUnboundFramebuffer(framebuffer);
  13581. var width = size.width || size;
  13582. var height = size.height || size;
  13583. var textures = [];
  13584. var attachments = [];
  13585. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13586. for (var i = 0; i < textureCount; i++) {
  13587. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13588. var type = types[i] || defaultType;
  13589. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13590. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13591. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13592. }
  13593. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13594. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13595. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13596. }
  13597. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13598. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13599. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13600. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13601. }
  13602. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13603. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13604. textures.push(texture);
  13605. attachments.push(attachment);
  13606. gl.activeTexture(gl["TEXTURE" + i]);
  13607. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13612. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13613. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13614. if (generateMipMaps) {
  13615. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13616. }
  13617. // Unbind
  13618. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13619. texture._framebuffer = framebuffer;
  13620. texture._depthStencilBuffer = depthStencilBuffer;
  13621. texture.baseWidth = width;
  13622. texture.baseHeight = height;
  13623. texture.width = width;
  13624. texture.height = height;
  13625. texture.isReady = true;
  13626. texture.samples = 1;
  13627. texture.generateMipMaps = generateMipMaps;
  13628. texture.samplingMode = samplingMode;
  13629. texture.type = type;
  13630. texture._generateDepthBuffer = generateDepthBuffer;
  13631. texture._generateStencilBuffer = generateStencilBuffer;
  13632. texture._attachments = attachments;
  13633. this._internalTexturesCache.push(texture);
  13634. }
  13635. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13636. // Depth texture
  13637. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13638. gl.activeTexture(gl.TEXTURE0);
  13639. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13640. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13641. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13642. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13644. 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);
  13645. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13646. depthTexture._framebuffer = framebuffer;
  13647. depthTexture.baseWidth = width;
  13648. depthTexture.baseHeight = height;
  13649. depthTexture.width = width;
  13650. depthTexture.height = height;
  13651. depthTexture.isReady = true;
  13652. depthTexture.samples = 1;
  13653. depthTexture.generateMipMaps = generateMipMaps;
  13654. depthTexture.samplingMode = gl.NEAREST;
  13655. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13656. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13657. textures.push(depthTexture);
  13658. this._internalTexturesCache.push(depthTexture);
  13659. }
  13660. gl.drawBuffers(attachments);
  13661. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13662. this.bindUnboundFramebuffer(null);
  13663. this.resetTextureCache();
  13664. return textures;
  13665. };
  13666. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13667. if (samples === void 0) { samples = 1; }
  13668. var depthStencilBuffer = null;
  13669. var gl = this._gl;
  13670. // Create the depth/stencil buffer
  13671. if (generateStencilBuffer) {
  13672. depthStencilBuffer = gl.createRenderbuffer();
  13673. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13674. if (samples > 1) {
  13675. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13676. }
  13677. else {
  13678. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13679. }
  13680. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13681. }
  13682. else if (generateDepthBuffer) {
  13683. depthStencilBuffer = gl.createRenderbuffer();
  13684. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13685. if (samples > 1) {
  13686. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13687. }
  13688. else {
  13689. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13690. }
  13691. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13692. }
  13693. return depthStencilBuffer;
  13694. };
  13695. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13696. if (this.webGLVersion < 2 || !texture) {
  13697. return 1;
  13698. }
  13699. if (texture.samples === samples) {
  13700. return samples;
  13701. }
  13702. var gl = this._gl;
  13703. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13704. // Dispose previous render buffers
  13705. if (texture._depthStencilBuffer) {
  13706. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13707. texture._depthStencilBuffer = null;
  13708. }
  13709. if (texture._MSAAFramebuffer) {
  13710. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13711. texture._MSAAFramebuffer = null;
  13712. }
  13713. if (texture._MSAARenderBuffer) {
  13714. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13715. texture._MSAARenderBuffer = null;
  13716. }
  13717. if (samples > 1) {
  13718. var framebuffer = gl.createFramebuffer();
  13719. if (!framebuffer) {
  13720. throw new Error("Unable to create multi sampled framebuffer");
  13721. }
  13722. texture._MSAAFramebuffer = framebuffer;
  13723. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13724. var colorRenderbuffer = gl.createRenderbuffer();
  13725. if (!colorRenderbuffer) {
  13726. throw new Error("Unable to create multi sampled framebuffer");
  13727. }
  13728. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13729. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13730. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13731. texture._MSAARenderBuffer = colorRenderbuffer;
  13732. }
  13733. else {
  13734. this.bindUnboundFramebuffer(texture._framebuffer);
  13735. }
  13736. texture.samples = samples;
  13737. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13738. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13739. this.bindUnboundFramebuffer(null);
  13740. return samples;
  13741. };
  13742. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13743. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13744. return 1;
  13745. }
  13746. if (textures[0].samples === samples) {
  13747. return samples;
  13748. }
  13749. var gl = this._gl;
  13750. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13751. // Dispose previous render buffers
  13752. if (textures[0]._depthStencilBuffer) {
  13753. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13754. textures[0]._depthStencilBuffer = null;
  13755. }
  13756. if (textures[0]._MSAAFramebuffer) {
  13757. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13758. textures[0]._MSAAFramebuffer = null;
  13759. }
  13760. for (var i = 0; i < textures.length; i++) {
  13761. if (textures[i]._MSAARenderBuffer) {
  13762. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13763. textures[i]._MSAARenderBuffer = null;
  13764. }
  13765. }
  13766. if (samples > 1) {
  13767. var framebuffer = gl.createFramebuffer();
  13768. if (!framebuffer) {
  13769. throw new Error("Unable to create multi sampled framebuffer");
  13770. }
  13771. this.bindUnboundFramebuffer(framebuffer);
  13772. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13773. var attachments = [];
  13774. for (var i = 0; i < textures.length; i++) {
  13775. var texture = textures[i];
  13776. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13777. var colorRenderbuffer = gl.createRenderbuffer();
  13778. if (!colorRenderbuffer) {
  13779. throw new Error("Unable to create multi sampled framebuffer");
  13780. }
  13781. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13782. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13783. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13784. texture._MSAAFramebuffer = framebuffer;
  13785. texture._MSAARenderBuffer = colorRenderbuffer;
  13786. texture.samples = samples;
  13787. texture._depthStencilBuffer = depthStencilBuffer;
  13788. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13789. attachments.push(attachment);
  13790. }
  13791. gl.drawBuffers(attachments);
  13792. }
  13793. else {
  13794. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13795. }
  13796. this.bindUnboundFramebuffer(null);
  13797. return samples;
  13798. };
  13799. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13800. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13801. };
  13802. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13803. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13804. };
  13805. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13806. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13807. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13808. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13809. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13810. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13811. }
  13812. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13813. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13814. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13815. }
  13816. var gl = this._gl;
  13817. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13818. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13819. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13820. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13821. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13822. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13823. }
  13824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13828. for (var face = 0; face < 6; face++) {
  13829. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13830. }
  13831. // Create the framebuffer
  13832. var framebuffer = gl.createFramebuffer();
  13833. this.bindUnboundFramebuffer(framebuffer);
  13834. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13835. // MipMaps
  13836. if (fullOptions.generateMipMaps) {
  13837. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13838. }
  13839. // Unbind
  13840. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13841. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13842. this.bindUnboundFramebuffer(null);
  13843. texture._framebuffer = framebuffer;
  13844. texture.width = size;
  13845. texture.height = size;
  13846. texture.isReady = true;
  13847. texture.isCube = true;
  13848. texture.samples = 1;
  13849. texture.generateMipMaps = fullOptions.generateMipMaps;
  13850. texture.samplingMode = fullOptions.samplingMode;
  13851. texture.type = fullOptions.type;
  13852. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13853. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13854. this._internalTexturesCache.push(texture);
  13855. return texture;
  13856. };
  13857. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13858. var _this = this;
  13859. if (onLoad === void 0) { onLoad = null; }
  13860. if (onError === void 0) { onError = null; }
  13861. if (forcedExtension === void 0) { forcedExtension = null; }
  13862. var callback = function (loadData) {
  13863. if (!loadData) {
  13864. if (onLoad) {
  13865. onLoad(null);
  13866. }
  13867. return;
  13868. }
  13869. var texture = loadData.texture;
  13870. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13871. texture._lodGenerationScale = scale;
  13872. texture._lodGenerationOffset = offset;
  13873. if (_this._caps.textureLOD) {
  13874. // Do not add extra process if texture lod is supported.
  13875. if (onLoad) {
  13876. onLoad(texture);
  13877. }
  13878. return;
  13879. }
  13880. var mipSlices = 3;
  13881. var gl = _this._gl;
  13882. var width = loadData.width;
  13883. if (!width) {
  13884. return;
  13885. }
  13886. var textures = [];
  13887. for (var i = 0; i < mipSlices; i++) {
  13888. //compute LOD from even spacing in smoothness (matching shader calculation)
  13889. var smoothness = i / (mipSlices - 1);
  13890. var roughness = 1 - smoothness;
  13891. var minLODIndex = offset; // roughness = 0
  13892. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13893. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13894. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13895. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13896. glTextureFromLod.isCube = true;
  13897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13902. if (loadData.isDDS) {
  13903. var info = loadData.info;
  13904. var data = loadData.data;
  13905. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13906. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13907. }
  13908. else {
  13909. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13910. }
  13911. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13912. // Wrap in a base texture for easy binding.
  13913. var lodTexture = new BABYLON.BaseTexture(scene);
  13914. lodTexture.isCube = true;
  13915. lodTexture._texture = glTextureFromLod;
  13916. glTextureFromLod.isReady = true;
  13917. textures.push(lodTexture);
  13918. }
  13919. texture._lodTextureHigh = textures[2];
  13920. texture._lodTextureMid = textures[1];
  13921. texture._lodTextureLow = textures[0];
  13922. if (onLoad) {
  13923. onLoad(texture);
  13924. }
  13925. };
  13926. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13927. };
  13928. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13929. var _this = this;
  13930. if (onLoad === void 0) { onLoad = null; }
  13931. if (onError === void 0) { onError = null; }
  13932. if (forcedExtension === void 0) { forcedExtension = null; }
  13933. var gl = this._gl;
  13934. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13935. texture.isCube = true;
  13936. texture.url = rootUrl;
  13937. texture.generateMipMaps = !noMipmap;
  13938. if (!this._doNotHandleContextLost) {
  13939. texture._extension = forcedExtension;
  13940. texture._files = files;
  13941. }
  13942. var isKTX = false;
  13943. var isDDS = false;
  13944. var lastDot = rootUrl.lastIndexOf('.');
  13945. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13946. if (this._textureFormatInUse) {
  13947. extension = this._textureFormatInUse;
  13948. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13949. isKTX = true;
  13950. }
  13951. else {
  13952. isDDS = (extension === ".dds");
  13953. }
  13954. var onerror = function (request, exception) {
  13955. if (onError && request) {
  13956. onError(request.status + " " + request.statusText, exception);
  13957. }
  13958. };
  13959. if (isKTX) {
  13960. this._loadFile(rootUrl, function (data) {
  13961. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13962. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13963. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13964. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13965. ktx.uploadLevels(_this._gl, !noMipmap);
  13966. _this.setCubeMapTextureParams(gl, loadMipmap);
  13967. texture.width = ktx.pixelWidth;
  13968. texture.height = ktx.pixelHeight;
  13969. texture.isReady = true;
  13970. }, undefined, undefined, true, onerror);
  13971. }
  13972. else if (isDDS) {
  13973. if (files && files.length === 6) {
  13974. this._cascadeLoadFiles(scene, function (imgs) {
  13975. var info;
  13976. var loadMipmap = false;
  13977. var width = 0;
  13978. for (var index = 0; index < imgs.length; index++) {
  13979. var data = imgs[index];
  13980. info = BABYLON.DDSTools.GetDDSInfo(data);
  13981. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13982. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13983. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13984. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13985. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13986. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13987. }
  13988. texture.width = info.width;
  13989. texture.height = info.height;
  13990. texture.type = info.textureType;
  13991. width = info.width;
  13992. }
  13993. _this.setCubeMapTextureParams(gl, loadMipmap);
  13994. texture.isReady = true;
  13995. if (onLoad) {
  13996. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13997. }
  13998. }, files, onError);
  13999. }
  14000. else {
  14001. this._loadFile(rootUrl, function (data) {
  14002. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14003. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14005. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14006. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14007. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14008. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14009. }
  14010. _this.setCubeMapTextureParams(gl, loadMipmap);
  14011. texture.width = info.width;
  14012. texture.height = info.height;
  14013. texture.isReady = true;
  14014. texture.type = info.textureType;
  14015. if (onLoad) {
  14016. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14017. }
  14018. }, undefined, undefined, true, onerror);
  14019. }
  14020. }
  14021. else {
  14022. if (!files) {
  14023. throw new Error("Cannot load cubemap because files were not defined");
  14024. }
  14025. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14026. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14027. var height = width;
  14028. _this._prepareWorkingCanvas();
  14029. if (!_this._workingCanvas || !_this._workingContext) {
  14030. return;
  14031. }
  14032. _this._workingCanvas.width = width;
  14033. _this._workingCanvas.height = height;
  14034. var faces = [
  14035. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14036. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14037. ];
  14038. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14039. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14040. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14041. for (var index = 0; index < faces.length; index++) {
  14042. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14043. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14044. }
  14045. if (!noMipmap) {
  14046. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14047. }
  14048. _this.setCubeMapTextureParams(gl, !noMipmap);
  14049. texture.width = width;
  14050. texture.height = height;
  14051. texture.isReady = true;
  14052. if (format) {
  14053. texture.format = format;
  14054. }
  14055. texture.onLoadedObservable.notifyObservers(texture);
  14056. texture.onLoadedObservable.clear();
  14057. if (onLoad) {
  14058. onLoad();
  14059. }
  14060. }, files, onError);
  14061. }
  14062. this._internalTexturesCache.push(texture);
  14063. return texture;
  14064. };
  14065. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14071. // this.resetTextureCache();
  14072. };
  14073. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14074. if (compression === void 0) { compression = null; }
  14075. if (level === void 0) { level = 0; }
  14076. texture._bufferViewArray = data;
  14077. texture.format = format;
  14078. texture.type = type;
  14079. texture.invertY = invertY;
  14080. texture._compression = compression;
  14081. var gl = this._gl;
  14082. var textureType = this._getWebGLTextureType(type);
  14083. var internalFormat = this._getInternalFormat(format);
  14084. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14085. var needConversion = false;
  14086. if (internalFormat === gl.RGB) {
  14087. internalFormat = gl.RGBA;
  14088. needConversion = true;
  14089. }
  14090. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14091. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14092. if (texture.width % 4 !== 0) {
  14093. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14094. }
  14095. // Data are known to be in +X +Y +Z -X -Y -Z
  14096. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14097. var faceData = data[faceIndex];
  14098. if (compression) {
  14099. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14100. }
  14101. else {
  14102. if (needConversion) {
  14103. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14104. }
  14105. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14106. }
  14107. }
  14108. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14109. if (isPot && texture.generateMipMaps && level === 0) {
  14110. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14111. }
  14112. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14113. // this.resetTextureCache();
  14114. texture.isReady = true;
  14115. };
  14116. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14117. if (compression === void 0) { compression = null; }
  14118. var gl = this._gl;
  14119. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14120. texture.isCube = true;
  14121. texture.generateMipMaps = generateMipMaps;
  14122. texture.format = format;
  14123. texture.type = type;
  14124. if (!this._doNotHandleContextLost) {
  14125. texture._bufferViewArray = data;
  14126. }
  14127. var textureType = this._getWebGLTextureType(type);
  14128. var internalFormat = this._getInternalFormat(format);
  14129. if (internalFormat === gl.RGB) {
  14130. internalFormat = gl.RGBA;
  14131. }
  14132. var width = size;
  14133. var height = width;
  14134. texture.width = width;
  14135. texture.height = height;
  14136. // Double check on POT to generate Mips.
  14137. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14138. if (!isPot) {
  14139. generateMipMaps = false;
  14140. }
  14141. // Upload data if needed. The texture won't be ready until then.
  14142. if (data) {
  14143. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14144. }
  14145. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14146. // Filters
  14147. if (data && generateMipMaps) {
  14148. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14149. }
  14150. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14153. }
  14154. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14157. }
  14158. else {
  14159. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14160. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14162. }
  14163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14165. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14166. return texture;
  14167. };
  14168. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14169. var _this = this;
  14170. if (onLoad === void 0) { onLoad = null; }
  14171. if (onError === void 0) { onError = null; }
  14172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14173. if (invertY === void 0) { invertY = false; }
  14174. var gl = this._gl;
  14175. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14176. scene._addPendingData(texture);
  14177. texture.url = url;
  14178. this._internalTexturesCache.push(texture);
  14179. var onerror = function (request, exception) {
  14180. scene._removePendingData(texture);
  14181. if (onError && request) {
  14182. onError(request.status + " " + request.statusText, exception);
  14183. }
  14184. };
  14185. var internalCallback = function (data) {
  14186. var width = texture.width;
  14187. var faceDataArrays = callback(data);
  14188. if (!faceDataArrays) {
  14189. return;
  14190. }
  14191. if (mipmmapGenerator) {
  14192. var textureType = _this._getWebGLTextureType(type);
  14193. var internalFormat = _this._getInternalFormat(format);
  14194. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14195. var needConversion = false;
  14196. if (internalFormat === gl.RGB) {
  14197. internalFormat = gl.RGBA;
  14198. needConversion = true;
  14199. }
  14200. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14201. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14202. var mipData = mipmmapGenerator(faceDataArrays);
  14203. for (var level = 0; level < mipData.length; level++) {
  14204. var mipSize = width >> level;
  14205. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14206. var mipFaceData = mipData[level][faceIndex];
  14207. if (needConversion) {
  14208. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14209. }
  14210. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14211. }
  14212. }
  14213. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14214. }
  14215. else {
  14216. texture.generateMipMaps = !noMipmap;
  14217. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14218. }
  14219. texture.isReady = true;
  14220. // this.resetTextureCache();
  14221. scene._removePendingData(texture);
  14222. if (onLoad) {
  14223. onLoad();
  14224. }
  14225. };
  14226. this._loadFile(url, function (data) {
  14227. internalCallback(data);
  14228. }, undefined, scene.database, true, onerror);
  14229. return texture;
  14230. };
  14231. ;
  14232. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14233. if (compression === void 0) { compression = null; }
  14234. var internalFormat = this._getInternalFormat(format);
  14235. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14236. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14237. if (!this._doNotHandleContextLost) {
  14238. texture._bufferView = data;
  14239. texture.format = format;
  14240. texture.invertY = invertY;
  14241. texture._compression = compression;
  14242. }
  14243. if (texture.width % 4 !== 0) {
  14244. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14245. }
  14246. if (compression && data) {
  14247. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14248. }
  14249. else {
  14250. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14251. }
  14252. if (texture.generateMipMaps) {
  14253. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14254. }
  14255. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14256. // this.resetTextureCache();
  14257. texture.isReady = true;
  14258. };
  14259. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14260. if (compression === void 0) { compression = null; }
  14261. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14262. texture.baseWidth = width;
  14263. texture.baseHeight = height;
  14264. texture.baseDepth = depth;
  14265. texture.width = width;
  14266. texture.height = height;
  14267. texture.depth = depth;
  14268. texture.format = format;
  14269. texture.generateMipMaps = generateMipMaps;
  14270. texture.samplingMode = samplingMode;
  14271. texture.is3D = true;
  14272. if (!this._doNotHandleContextLost) {
  14273. texture._bufferView = data;
  14274. }
  14275. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14276. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14277. // Filters
  14278. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14279. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14281. if (generateMipMaps) {
  14282. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14283. }
  14284. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14285. this._internalTexturesCache.push(texture);
  14286. return texture;
  14287. };
  14288. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14289. var gl = this._gl;
  14290. if (!gl) {
  14291. return;
  14292. }
  14293. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14296. if (!noMipmap && !isCompressed) {
  14297. gl.generateMipmap(gl.TEXTURE_2D);
  14298. }
  14299. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14300. // this.resetTextureCache();
  14301. if (scene) {
  14302. scene._removePendingData(texture);
  14303. }
  14304. texture.onLoadedObservable.notifyObservers(texture);
  14305. texture.onLoadedObservable.clear();
  14306. };
  14307. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14308. var _this = this;
  14309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14310. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14311. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14312. var gl = this._gl;
  14313. if (!gl) {
  14314. return;
  14315. }
  14316. if (!texture._webGLTexture) {
  14317. // this.resetTextureCache();
  14318. if (scene) {
  14319. scene._removePendingData(texture);
  14320. }
  14321. return;
  14322. }
  14323. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14324. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14325. texture.baseWidth = width;
  14326. texture.baseHeight = height;
  14327. texture.width = potWidth;
  14328. texture.height = potHeight;
  14329. texture.isReady = true;
  14330. if (processFunction(potWidth, potHeight, function () {
  14331. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14332. })) {
  14333. // Returning as texture needs extra async steps
  14334. return;
  14335. }
  14336. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14337. };
  14338. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14339. // Create new RGBA data container.
  14340. var rgbaData;
  14341. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14342. rgbaData = new Float32Array(width * height * 4);
  14343. }
  14344. else {
  14345. rgbaData = new Uint32Array(width * height * 4);
  14346. }
  14347. // Convert each pixel.
  14348. for (var x = 0; x < width; x++) {
  14349. for (var y = 0; y < height; y++) {
  14350. var index = (y * width + x) * 3;
  14351. var newIndex = (y * width + x) * 4;
  14352. // Map Old Value to new value.
  14353. rgbaData[newIndex + 0] = rgbData[index + 0];
  14354. rgbaData[newIndex + 1] = rgbData[index + 1];
  14355. rgbaData[newIndex + 2] = rgbData[index + 2];
  14356. // Add fully opaque alpha channel.
  14357. rgbaData[newIndex + 3] = 1;
  14358. }
  14359. }
  14360. return rgbaData;
  14361. };
  14362. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14363. var gl = this._gl;
  14364. if (texture._framebuffer) {
  14365. gl.deleteFramebuffer(texture._framebuffer);
  14366. texture._framebuffer = null;
  14367. }
  14368. if (texture._depthStencilBuffer) {
  14369. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14370. texture._depthStencilBuffer = null;
  14371. }
  14372. if (texture._MSAAFramebuffer) {
  14373. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14374. texture._MSAAFramebuffer = null;
  14375. }
  14376. if (texture._MSAARenderBuffer) {
  14377. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14378. texture._MSAARenderBuffer = null;
  14379. }
  14380. };
  14381. Engine.prototype._releaseTexture = function (texture) {
  14382. var gl = this._gl;
  14383. this._releaseFramebufferObjects(texture);
  14384. gl.deleteTexture(texture._webGLTexture);
  14385. // Unbind channels
  14386. this.unbindAllTextures();
  14387. var index = this._internalTexturesCache.indexOf(texture);
  14388. if (index !== -1) {
  14389. this._internalTexturesCache.splice(index, 1);
  14390. }
  14391. // Integrated fixed lod samplers.
  14392. if (texture._lodTextureHigh) {
  14393. texture._lodTextureHigh.dispose();
  14394. }
  14395. if (texture._lodTextureMid) {
  14396. texture._lodTextureMid.dispose();
  14397. }
  14398. if (texture._lodTextureLow) {
  14399. texture._lodTextureLow.dispose();
  14400. }
  14401. };
  14402. Engine.prototype.setProgram = function (program) {
  14403. if (this._currentProgram !== program) {
  14404. this._gl.useProgram(program);
  14405. this._currentProgram = program;
  14406. }
  14407. };
  14408. Engine.prototype.bindSamplers = function (effect) {
  14409. this.setProgram(effect.getProgram());
  14410. var samplers = effect.getSamplers();
  14411. for (var index = 0; index < samplers.length; index++) {
  14412. var uniform = effect.getUniform(samplers[index]);
  14413. if (uniform) {
  14414. this._boundUniforms[index] = uniform;
  14415. }
  14416. }
  14417. this._currentEffect = null;
  14418. };
  14419. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14420. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14421. return;
  14422. }
  14423. // Remove
  14424. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14425. // Bind last to it
  14426. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14427. // Bind to dummy
  14428. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14429. };
  14430. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14431. if (!internalTexture) {
  14432. return -1;
  14433. }
  14434. internalTexture._initialSlot = channel;
  14435. if (this.disableTextureBindingOptimization) {
  14436. if (channel !== internalTexture._designatedSlot) {
  14437. this._textureCollisions.addCount(1, false);
  14438. }
  14439. }
  14440. else {
  14441. if (channel !== internalTexture._designatedSlot) {
  14442. if (internalTexture._designatedSlot > -1) {
  14443. return internalTexture._designatedSlot;
  14444. }
  14445. else {
  14446. // No slot for this texture, let's pick a new one (if we find a free slot)
  14447. if (this._nextFreeTextureSlots.length) {
  14448. return this._nextFreeTextureSlots[0];
  14449. }
  14450. // We need to recycle the oldest bound texture, sorry.
  14451. this._textureCollisions.addCount(1, false);
  14452. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14453. }
  14454. }
  14455. }
  14456. return channel;
  14457. };
  14458. Engine.prototype._linkTrackers = function (previous, next) {
  14459. previous.next = next;
  14460. next.previous = previous;
  14461. };
  14462. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14463. var currentSlot = internalTexture._designatedSlot;
  14464. if (currentSlot === -1) {
  14465. return -1;
  14466. }
  14467. internalTexture._designatedSlot = -1;
  14468. if (this.disableTextureBindingOptimization) {
  14469. return -1;
  14470. }
  14471. // Remove from bound list
  14472. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14473. // Free the slot
  14474. this._boundTexturesCache[currentSlot] = null;
  14475. this._nextFreeTextureSlots.push(currentSlot);
  14476. return currentSlot;
  14477. };
  14478. Engine.prototype._activateCurrentTexture = function () {
  14479. if (this._currentTextureChannel !== this._activeChannel) {
  14480. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14481. this._currentTextureChannel = this._activeChannel;
  14482. }
  14483. };
  14484. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14485. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14486. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14487. this._activeChannel = texture._designatedSlot;
  14488. }
  14489. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14490. var isTextureForRendering = texture && texture._initialSlot > -1;
  14491. if (currentTextureBound !== texture) {
  14492. if (currentTextureBound) {
  14493. this._removeDesignatedSlot(currentTextureBound);
  14494. }
  14495. this._activateCurrentTexture();
  14496. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14497. this._boundTexturesCache[this._activeChannel] = texture;
  14498. if (texture) {
  14499. if (!this.disableTextureBindingOptimization) {
  14500. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14501. if (slotIndex > -1) {
  14502. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14503. }
  14504. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14505. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14506. }
  14507. texture._designatedSlot = this._activeChannel;
  14508. }
  14509. }
  14510. else if (forTextureDataUpdate) {
  14511. this._activateCurrentTexture();
  14512. }
  14513. if (isTextureForRendering && !forTextureDataUpdate) {
  14514. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14515. }
  14516. };
  14517. Engine.prototype._bindTexture = function (channel, texture) {
  14518. if (channel < 0) {
  14519. return;
  14520. }
  14521. if (texture) {
  14522. channel = this._getCorrectTextureChannel(channel, texture);
  14523. }
  14524. this._activeChannel = channel;
  14525. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14526. };
  14527. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14528. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14529. };
  14530. Engine.prototype.unbindAllTextures = function () {
  14531. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14532. this._activeChannel = channel;
  14533. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14534. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14535. if (this.webGLVersion > 1) {
  14536. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14537. }
  14538. }
  14539. };
  14540. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14541. if (channel < 0) {
  14542. return;
  14543. }
  14544. if (uniform) {
  14545. this._boundUniforms[channel] = uniform;
  14546. }
  14547. this._setTexture(channel, texture);
  14548. };
  14549. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14550. var uniform = this._boundUniforms[sourceSlot];
  14551. if (uniform._currentState === destination) {
  14552. return;
  14553. }
  14554. this._gl.uniform1i(uniform, destination);
  14555. uniform._currentState = destination;
  14556. };
  14557. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14558. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14559. // Not ready?
  14560. if (!texture) {
  14561. if (this._boundTexturesCache[channel] != null) {
  14562. this._activeChannel = channel;
  14563. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14564. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14565. if (this.webGLVersion > 1) {
  14566. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14567. }
  14568. }
  14569. return false;
  14570. }
  14571. // Video
  14572. if (texture.video) {
  14573. this._activeChannel = channel;
  14574. texture.update();
  14575. }
  14576. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14577. texture.delayLoad();
  14578. return false;
  14579. }
  14580. var internalTexture;
  14581. if (texture.isReady()) {
  14582. internalTexture = texture.getInternalTexture();
  14583. }
  14584. else if (texture.isCube) {
  14585. internalTexture = this.emptyCubeTexture;
  14586. }
  14587. else if (texture.is3D) {
  14588. internalTexture = this.emptyTexture3D;
  14589. }
  14590. else {
  14591. internalTexture = this.emptyTexture;
  14592. }
  14593. if (!isPartOfTextureArray) {
  14594. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14595. }
  14596. if (this._boundTexturesCache[channel] === internalTexture) {
  14597. this._moveBoundTextureOnTop(internalTexture);
  14598. if (!isPartOfTextureArray) {
  14599. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14600. }
  14601. return false;
  14602. }
  14603. this._activeChannel = channel;
  14604. if (internalTexture && internalTexture.is3D) {
  14605. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14606. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14607. internalTexture._cachedWrapU = texture.wrapU;
  14608. switch (texture.wrapU) {
  14609. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14610. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14611. break;
  14612. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14613. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14614. break;
  14615. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14616. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14617. break;
  14618. }
  14619. }
  14620. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14621. internalTexture._cachedWrapV = texture.wrapV;
  14622. switch (texture.wrapV) {
  14623. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14624. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14625. break;
  14626. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14627. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14628. break;
  14629. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14630. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14631. break;
  14632. }
  14633. }
  14634. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14635. internalTexture._cachedWrapR = texture.wrapR;
  14636. switch (texture.wrapR) {
  14637. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14638. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14639. break;
  14640. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14641. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14642. break;
  14643. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14644. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14645. break;
  14646. }
  14647. }
  14648. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14649. }
  14650. else if (internalTexture && internalTexture.isCube) {
  14651. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14652. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14653. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14654. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14655. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14656. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14658. }
  14659. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14660. }
  14661. else {
  14662. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14663. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14664. internalTexture._cachedWrapU = texture.wrapU;
  14665. switch (texture.wrapU) {
  14666. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14667. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14668. break;
  14669. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14670. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14671. break;
  14672. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14673. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14674. break;
  14675. }
  14676. }
  14677. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14678. internalTexture._cachedWrapV = texture.wrapV;
  14679. switch (texture.wrapV) {
  14680. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14682. break;
  14683. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14684. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14685. break;
  14686. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14687. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14688. break;
  14689. }
  14690. }
  14691. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14692. }
  14693. return true;
  14694. };
  14695. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14696. if (channel < 0 || !uniform) {
  14697. return;
  14698. }
  14699. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14700. this._textureUnits = new Int32Array(textures.length);
  14701. }
  14702. for (var i = 0; i < textures.length; i++) {
  14703. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14704. }
  14705. this._gl.uniform1iv(uniform, this._textureUnits);
  14706. for (var index = 0; index < textures.length; index++) {
  14707. this._setTexture(this._textureUnits[index], textures[index], true);
  14708. }
  14709. };
  14710. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14711. var internalTexture = texture.getInternalTexture();
  14712. if (!internalTexture) {
  14713. return;
  14714. }
  14715. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14716. var value = texture.anisotropicFilteringLevel;
  14717. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14718. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14719. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14720. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14721. }
  14722. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14723. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14724. internalTexture._cachedAnisotropicFilteringLevel = value;
  14725. }
  14726. };
  14727. Engine.prototype.readPixels = function (x, y, width, height) {
  14728. var data = new Uint8Array(height * width * 4);
  14729. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14730. return data;
  14731. };
  14732. /**
  14733. * Add an externaly attached data from its key.
  14734. * This method call will fail and return false, if such key already exists.
  14735. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14736. * @param key the unique key that identifies the data
  14737. * @param data the data object to associate to the key for this Engine instance
  14738. * @return true if no such key were already present and the data was added successfully, false otherwise
  14739. */
  14740. Engine.prototype.addExternalData = function (key, data) {
  14741. if (!this._externalData) {
  14742. this._externalData = new BABYLON.StringDictionary();
  14743. }
  14744. return this._externalData.add(key, data);
  14745. };
  14746. /**
  14747. * Get an externaly attached data from its key
  14748. * @param key the unique key that identifies the data
  14749. * @return the associated data, if present (can be null), or undefined if not present
  14750. */
  14751. Engine.prototype.getExternalData = function (key) {
  14752. if (!this._externalData) {
  14753. this._externalData = new BABYLON.StringDictionary();
  14754. }
  14755. return this._externalData.get(key);
  14756. };
  14757. /**
  14758. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14759. * @param key the unique key that identifies the data
  14760. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14761. * @return the associated data, can be null if the factory returned null.
  14762. */
  14763. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14764. if (!this._externalData) {
  14765. this._externalData = new BABYLON.StringDictionary();
  14766. }
  14767. return this._externalData.getOrAddWithFactory(key, factory);
  14768. };
  14769. /**
  14770. * Remove an externaly attached data from the Engine instance
  14771. * @param key the unique key that identifies the data
  14772. * @return true if the data was successfully removed, false if it doesn't exist
  14773. */
  14774. Engine.prototype.removeExternalData = function (key) {
  14775. if (!this._externalData) {
  14776. this._externalData = new BABYLON.StringDictionary();
  14777. }
  14778. return this._externalData.remove(key);
  14779. };
  14780. Engine.prototype.unbindAllAttributes = function () {
  14781. if (this._mustWipeVertexAttributes) {
  14782. this._mustWipeVertexAttributes = false;
  14783. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14784. this._gl.disableVertexAttribArray(i);
  14785. this._vertexAttribArraysEnabled[i] = false;
  14786. this._currentBufferPointers[i].active = false;
  14787. }
  14788. return;
  14789. }
  14790. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14791. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14792. continue;
  14793. }
  14794. this._gl.disableVertexAttribArray(i);
  14795. this._vertexAttribArraysEnabled[i] = false;
  14796. this._currentBufferPointers[i].active = false;
  14797. }
  14798. };
  14799. Engine.prototype.releaseEffects = function () {
  14800. for (var name in this._compiledEffects) {
  14801. this._deleteProgram(this._compiledEffects[name]._program);
  14802. }
  14803. this._compiledEffects = {};
  14804. };
  14805. // Dispose
  14806. Engine.prototype.dispose = function () {
  14807. this.hideLoadingUI();
  14808. this.stopRenderLoop();
  14809. // Release postProcesses
  14810. while (this.postProcesses.length) {
  14811. this.postProcesses[0].dispose();
  14812. }
  14813. // Empty texture
  14814. if (this._emptyTexture) {
  14815. this._releaseTexture(this._emptyTexture);
  14816. this._emptyTexture = null;
  14817. }
  14818. if (this._emptyCubeTexture) {
  14819. this._releaseTexture(this._emptyCubeTexture);
  14820. this._emptyCubeTexture = null;
  14821. }
  14822. // Rescale PP
  14823. if (this._rescalePostProcess) {
  14824. this._rescalePostProcess.dispose();
  14825. }
  14826. // Release scenes
  14827. while (this.scenes.length) {
  14828. this.scenes[0].dispose();
  14829. }
  14830. // Release audio engine
  14831. if (Engine.audioEngine) {
  14832. Engine.audioEngine.dispose();
  14833. }
  14834. // Release effects
  14835. this.releaseEffects();
  14836. // Unbind
  14837. this.unbindAllAttributes();
  14838. if (this._dummyFramebuffer) {
  14839. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14840. }
  14841. //WebVR
  14842. this.disableVR();
  14843. // Events
  14844. if (BABYLON.Tools.IsWindowObjectExist()) {
  14845. window.removeEventListener("blur", this._onBlur);
  14846. window.removeEventListener("focus", this._onFocus);
  14847. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14848. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14849. if (this._renderingCanvas) {
  14850. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14851. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14852. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14853. if (!this._doNotHandleContextLost) {
  14854. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14855. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14856. }
  14857. }
  14858. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14859. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14860. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14861. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14862. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14863. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14864. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14865. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14866. if (this._onVrDisplayConnect) {
  14867. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14868. if (this._onVrDisplayDisconnect) {
  14869. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14870. }
  14871. if (this._onVrDisplayPresentChange) {
  14872. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14873. }
  14874. this._onVrDisplayConnect = null;
  14875. this._onVrDisplayDisconnect = null;
  14876. }
  14877. }
  14878. // Remove from Instances
  14879. var index = Engine.Instances.indexOf(this);
  14880. if (index >= 0) {
  14881. Engine.Instances.splice(index, 1);
  14882. }
  14883. this._workingCanvas = null;
  14884. this._workingContext = null;
  14885. this._currentBufferPointers = [];
  14886. this._renderingCanvas = null;
  14887. this._currentProgram = null;
  14888. this._bindedRenderFunction = null;
  14889. this.onResizeObservable.clear();
  14890. this.onCanvasBlurObservable.clear();
  14891. this.onCanvasFocusObservable.clear();
  14892. this.onCanvasPointerOutObservable.clear();
  14893. this.onBeginFrameObservable.clear();
  14894. this.onEndFrameObservable.clear();
  14895. BABYLON.Effect.ResetCache();
  14896. // Abort active requests
  14897. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14898. var request = _a[_i];
  14899. request.abort();
  14900. }
  14901. };
  14902. // Loading screen
  14903. Engine.prototype.displayLoadingUI = function () {
  14904. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14905. return;
  14906. }
  14907. var loadingScreen = this.loadingScreen;
  14908. if (loadingScreen) {
  14909. loadingScreen.displayLoadingUI();
  14910. }
  14911. };
  14912. Engine.prototype.hideLoadingUI = function () {
  14913. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14914. return;
  14915. }
  14916. var loadingScreen = this.loadingScreen;
  14917. if (loadingScreen) {
  14918. loadingScreen.hideLoadingUI();
  14919. }
  14920. };
  14921. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14922. get: function () {
  14923. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14924. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14925. return this._loadingScreen;
  14926. },
  14927. set: function (loadingScreen) {
  14928. this._loadingScreen = loadingScreen;
  14929. },
  14930. enumerable: true,
  14931. configurable: true
  14932. });
  14933. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14934. set: function (text) {
  14935. this.loadingScreen.loadingUIText = text;
  14936. },
  14937. enumerable: true,
  14938. configurable: true
  14939. });
  14940. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14941. set: function (color) {
  14942. this.loadingScreen.loadingUIBackgroundColor = color;
  14943. },
  14944. enumerable: true,
  14945. configurable: true
  14946. });
  14947. Engine.prototype.attachContextLostEvent = function (callback) {
  14948. if (this._renderingCanvas) {
  14949. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14950. }
  14951. };
  14952. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14953. if (this._renderingCanvas) {
  14954. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14955. }
  14956. };
  14957. Engine.prototype.getVertexShaderSource = function (program) {
  14958. var shaders = this._gl.getAttachedShaders(program);
  14959. if (!shaders) {
  14960. return null;
  14961. }
  14962. return this._gl.getShaderSource(shaders[0]);
  14963. };
  14964. Engine.prototype.getFragmentShaderSource = function (program) {
  14965. var shaders = this._gl.getAttachedShaders(program);
  14966. if (!shaders) {
  14967. return null;
  14968. }
  14969. return this._gl.getShaderSource(shaders[1]);
  14970. };
  14971. Engine.prototype.getError = function () {
  14972. return this._gl.getError();
  14973. };
  14974. // FPS
  14975. Engine.prototype.getFps = function () {
  14976. return this._fps;
  14977. };
  14978. Engine.prototype.getDeltaTime = function () {
  14979. return this._deltaTime;
  14980. };
  14981. Engine.prototype._measureFps = function () {
  14982. this._performanceMonitor.sampleFrame();
  14983. this._fps = this._performanceMonitor.averageFPS;
  14984. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14985. };
  14986. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14987. if (faceIndex === void 0) { faceIndex = -1; }
  14988. var gl = this._gl;
  14989. if (!this._dummyFramebuffer) {
  14990. var dummy = gl.createFramebuffer();
  14991. if (!dummy) {
  14992. throw new Error("Unable to create dummy framebuffer");
  14993. }
  14994. this._dummyFramebuffer = dummy;
  14995. }
  14996. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14997. if (faceIndex > -1) {
  14998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14999. }
  15000. else {
  15001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15002. }
  15003. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15004. var buffer;
  15005. switch (readType) {
  15006. case gl.UNSIGNED_BYTE:
  15007. buffer = new Uint8Array(4 * width * height);
  15008. readType = gl.UNSIGNED_BYTE;
  15009. break;
  15010. default:
  15011. buffer = new Float32Array(4 * width * height);
  15012. readType = gl.FLOAT;
  15013. break;
  15014. }
  15015. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15016. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15017. return buffer;
  15018. };
  15019. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15020. if (this._webGLVersion > 1) {
  15021. return this._caps.colorBufferFloat;
  15022. }
  15023. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15024. };
  15025. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15026. if (this._webGLVersion > 1) {
  15027. return this._caps.colorBufferFloat;
  15028. }
  15029. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15030. };
  15031. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15032. Engine.prototype._canRenderToFramebuffer = function (type) {
  15033. var gl = this._gl;
  15034. //clear existing errors
  15035. while (gl.getError() !== gl.NO_ERROR) { }
  15036. var successful = true;
  15037. var texture = gl.createTexture();
  15038. gl.bindTexture(gl.TEXTURE_2D, texture);
  15039. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15042. var fb = gl.createFramebuffer();
  15043. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15044. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15045. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15046. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15047. successful = successful && (gl.getError() === gl.NO_ERROR);
  15048. //try render by clearing frame buffer's color buffer
  15049. if (successful) {
  15050. gl.clear(gl.COLOR_BUFFER_BIT);
  15051. successful = successful && (gl.getError() === gl.NO_ERROR);
  15052. }
  15053. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15054. if (successful) {
  15055. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15056. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15057. var readFormat = gl.RGBA;
  15058. var readType = gl.UNSIGNED_BYTE;
  15059. var buffer = new Uint8Array(4);
  15060. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15061. successful = successful && (gl.getError() === gl.NO_ERROR);
  15062. }
  15063. //clean up
  15064. gl.deleteTexture(texture);
  15065. gl.deleteFramebuffer(fb);
  15066. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15067. //clear accumulated errors
  15068. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15069. return successful;
  15070. };
  15071. Engine.prototype._getWebGLTextureType = function (type) {
  15072. if (type === Engine.TEXTURETYPE_FLOAT) {
  15073. return this._gl.FLOAT;
  15074. }
  15075. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15076. // Add Half Float Constant.
  15077. return this._gl.HALF_FLOAT_OES;
  15078. }
  15079. return this._gl.UNSIGNED_BYTE;
  15080. };
  15081. ;
  15082. /** @ignore */
  15083. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15084. if (this._webGLVersion === 1) {
  15085. return this._gl.RGBA;
  15086. }
  15087. if (type === Engine.TEXTURETYPE_FLOAT) {
  15088. if (format) {
  15089. switch (format) {
  15090. case Engine.TEXTUREFORMAT_R32F:
  15091. return this._gl.R32F;
  15092. case Engine.TEXTUREFORMAT_RG32F:
  15093. return this._gl.RG32F;
  15094. case Engine.TEXTUREFORMAT_RGB32F:
  15095. return this._gl.RGB32F;
  15096. }
  15097. }
  15098. return this._gl.RGBA32F;
  15099. }
  15100. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15101. return this._gl.RGBA16F;
  15102. }
  15103. return this._gl.RGBA;
  15104. };
  15105. ;
  15106. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15107. if (type === Engine.TEXTURETYPE_FLOAT) {
  15108. return this._gl.RGBA32F;
  15109. }
  15110. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15111. return this._gl.RGBA16F;
  15112. }
  15113. return this._gl.RGBA8;
  15114. };
  15115. ;
  15116. Engine.prototype.createQuery = function () {
  15117. return this._gl.createQuery();
  15118. };
  15119. Engine.prototype.deleteQuery = function (query) {
  15120. this._gl.deleteQuery(query);
  15121. return this;
  15122. };
  15123. Engine.prototype.isQueryResultAvailable = function (query) {
  15124. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15125. };
  15126. Engine.prototype.getQueryResult = function (query) {
  15127. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15128. };
  15129. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15130. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15131. this._gl.beginQuery(glAlgorithm, query);
  15132. return this;
  15133. };
  15134. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15135. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15136. this._gl.endQuery(glAlgorithm);
  15137. return this;
  15138. };
  15139. /* Time queries */
  15140. Engine.prototype._createTimeQuery = function () {
  15141. var timerQuery = this._caps.timerQuery;
  15142. if (timerQuery.createQueryEXT) {
  15143. return timerQuery.createQueryEXT();
  15144. }
  15145. return this.createQuery();
  15146. };
  15147. Engine.prototype._deleteTimeQuery = function (query) {
  15148. var timerQuery = this._caps.timerQuery;
  15149. if (timerQuery.deleteQueryEXT) {
  15150. timerQuery.deleteQueryEXT(query);
  15151. return;
  15152. }
  15153. this.deleteQuery(query);
  15154. };
  15155. Engine.prototype._getTimeQueryResult = function (query) {
  15156. var timerQuery = this._caps.timerQuery;
  15157. if (timerQuery.getQueryObjectEXT) {
  15158. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15159. }
  15160. return this.getQueryResult(query);
  15161. };
  15162. Engine.prototype._getTimeQueryAvailability = function (query) {
  15163. var timerQuery = this._caps.timerQuery;
  15164. if (timerQuery.getQueryObjectEXT) {
  15165. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15166. }
  15167. return this.isQueryResultAvailable(query);
  15168. };
  15169. Engine.prototype.startTimeQuery = function () {
  15170. var timerQuery = this._caps.timerQuery;
  15171. if (!timerQuery) {
  15172. return null;
  15173. }
  15174. var token = new BABYLON._TimeToken();
  15175. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15176. if (this._caps.canUseTimestampForTimerQuery) {
  15177. token._startTimeQuery = this._createTimeQuery();
  15178. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15179. }
  15180. else {
  15181. if (this._currentNonTimestampToken) {
  15182. return this._currentNonTimestampToken;
  15183. }
  15184. token._timeElapsedQuery = this._createTimeQuery();
  15185. if (timerQuery.beginQueryEXT) {
  15186. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15187. }
  15188. else {
  15189. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15190. }
  15191. this._currentNonTimestampToken = token;
  15192. }
  15193. return token;
  15194. };
  15195. Engine.prototype.endTimeQuery = function (token) {
  15196. var timerQuery = this._caps.timerQuery;
  15197. if (!timerQuery || !token) {
  15198. return -1;
  15199. }
  15200. if (this._caps.canUseTimestampForTimerQuery) {
  15201. if (!token._startTimeQuery) {
  15202. return -1;
  15203. }
  15204. if (!token._endTimeQuery) {
  15205. token._endTimeQuery = this._createTimeQuery();
  15206. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15207. }
  15208. }
  15209. else if (!token._timeElapsedQueryEnded) {
  15210. if (!token._timeElapsedQuery) {
  15211. return -1;
  15212. }
  15213. if (timerQuery.endQueryEXT) {
  15214. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15215. }
  15216. else {
  15217. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15218. }
  15219. token._timeElapsedQueryEnded = true;
  15220. }
  15221. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15222. var available = false;
  15223. if (token._endTimeQuery) {
  15224. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15225. }
  15226. else if (token._timeElapsedQuery) {
  15227. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15228. }
  15229. if (available && !disjoint) {
  15230. var result = 0;
  15231. if (this._caps.canUseTimestampForTimerQuery) {
  15232. if (!token._startTimeQuery || !token._endTimeQuery) {
  15233. return -1;
  15234. }
  15235. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15236. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15237. result = timeEnd - timeStart;
  15238. this._deleteTimeQuery(token._startTimeQuery);
  15239. this._deleteTimeQuery(token._endTimeQuery);
  15240. token._startTimeQuery = null;
  15241. token._endTimeQuery = null;
  15242. }
  15243. else {
  15244. if (!token._timeElapsedQuery) {
  15245. return -1;
  15246. }
  15247. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15248. this._deleteTimeQuery(token._timeElapsedQuery);
  15249. token._timeElapsedQuery = null;
  15250. token._timeElapsedQueryEnded = false;
  15251. this._currentNonTimestampToken = null;
  15252. }
  15253. return result;
  15254. }
  15255. return -1;
  15256. };
  15257. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15258. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15259. };
  15260. // Transform feedback
  15261. Engine.prototype.createTransformFeedback = function () {
  15262. return this._gl.createTransformFeedback();
  15263. };
  15264. Engine.prototype.deleteTransformFeedback = function (value) {
  15265. this._gl.deleteTransformFeedback(value);
  15266. };
  15267. Engine.prototype.bindTransformFeedback = function (value) {
  15268. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15269. };
  15270. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15271. if (usePoints === void 0) { usePoints = true; }
  15272. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15273. };
  15274. Engine.prototype.endTransformFeedback = function () {
  15275. this._gl.endTransformFeedback();
  15276. };
  15277. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15278. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15279. };
  15280. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15281. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15282. };
  15283. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15284. var _this = this;
  15285. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15286. this._activeRequests.push(request);
  15287. request.onCompleteObservable.add(function (request) {
  15288. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15289. });
  15290. return request;
  15291. };
  15292. /** @ignore */
  15293. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15294. var _this = this;
  15295. return new Promise(function (resolve, reject) {
  15296. _this._loadFile(url, function (data) {
  15297. resolve(data);
  15298. }, undefined, database, useArrayBuffer, function (request, exception) {
  15299. reject(exception);
  15300. });
  15301. });
  15302. };
  15303. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15304. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15305. var onload = function (data) {
  15306. loadedFiles[index] = data;
  15307. loadedFiles._internalCount++;
  15308. if (loadedFiles._internalCount === 6) {
  15309. onfinish(loadedFiles);
  15310. }
  15311. };
  15312. var onerror = function (request, exception) {
  15313. if (onErrorCallBack && request) {
  15314. onErrorCallBack(request.status + " " + request.statusText, exception);
  15315. }
  15316. };
  15317. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15318. };
  15319. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15320. if (onError === void 0) { onError = null; }
  15321. var loadedFiles = [];
  15322. loadedFiles._internalCount = 0;
  15323. for (var index = 0; index < 6; index++) {
  15324. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15325. }
  15326. };
  15327. // Statics
  15328. Engine.isSupported = function () {
  15329. try {
  15330. var tempcanvas = document.createElement("canvas");
  15331. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15332. return gl != null && !!window.WebGLRenderingContext;
  15333. }
  15334. catch (e) {
  15335. return false;
  15336. }
  15337. };
  15338. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15339. Engine.ExceptionList = [
  15340. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15341. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15342. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15343. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15344. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15345. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15346. ];
  15347. Engine.Instances = new Array();
  15348. // Const statics
  15349. Engine._ALPHA_DISABLE = 0;
  15350. Engine._ALPHA_ADD = 1;
  15351. Engine._ALPHA_COMBINE = 2;
  15352. Engine._ALPHA_SUBTRACT = 3;
  15353. Engine._ALPHA_MULTIPLY = 4;
  15354. Engine._ALPHA_MAXIMIZED = 5;
  15355. Engine._ALPHA_ONEONE = 6;
  15356. Engine._ALPHA_PREMULTIPLIED = 7;
  15357. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15358. Engine._ALPHA_INTERPOLATE = 9;
  15359. Engine._ALPHA_SCREENMODE = 10;
  15360. Engine._DELAYLOADSTATE_NONE = 0;
  15361. Engine._DELAYLOADSTATE_LOADED = 1;
  15362. Engine._DELAYLOADSTATE_LOADING = 2;
  15363. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15364. Engine._TEXTUREFORMAT_ALPHA = 0;
  15365. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15366. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15367. Engine._TEXTUREFORMAT_RGB = 4;
  15368. Engine._TEXTUREFORMAT_RGBA = 5;
  15369. Engine._TEXTUREFORMAT_R32F = 6;
  15370. Engine._TEXTUREFORMAT_RG32F = 7;
  15371. Engine._TEXTUREFORMAT_RGB32F = 8;
  15372. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15373. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15374. Engine._TEXTURETYPE_FLOAT = 1;
  15375. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15376. // Depht or Stencil test Constants.
  15377. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15378. 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.
  15379. 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.
  15380. 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.
  15381. 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.
  15382. 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.
  15383. 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.
  15384. 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.
  15385. // Stencil Actions Constants.
  15386. Engine._KEEP = 0x1E00;
  15387. Engine._REPLACE = 0x1E01;
  15388. Engine._INCR = 0x1E02;
  15389. Engine._DECR = 0x1E03;
  15390. Engine._INVERT = 0x150A;
  15391. Engine._INCR_WRAP = 0x8507;
  15392. Engine._DECR_WRAP = 0x8508;
  15393. // Texture rescaling mode
  15394. Engine._SCALEMODE_FLOOR = 1;
  15395. Engine._SCALEMODE_NEAREST = 2;
  15396. Engine._SCALEMODE_CEILING = 3;
  15397. // Updatable statics so stick with vars here
  15398. Engine.CollisionsEpsilon = 0.001;
  15399. Engine.CodeRepository = "src/";
  15400. Engine.ShadersRepository = "src/Shaders/";
  15401. return Engine;
  15402. }());
  15403. BABYLON.Engine = Engine;
  15404. })(BABYLON || (BABYLON = {}));
  15405. //# sourceMappingURL=babylon.engine.js.map
  15406. var BABYLON;
  15407. (function (BABYLON) {
  15408. /**
  15409. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15410. */
  15411. var Node = /** @class */ (function () {
  15412. /**
  15413. * Creates a new Node
  15414. * @param {string} name - the name and id to be given to this node
  15415. * @param {BABYLON.Scene} the scene this node will be added to
  15416. */
  15417. function Node(name, scene) {
  15418. if (scene === void 0) { scene = null; }
  15419. /**
  15420. * Gets or sets a string used to store user defined state for the node
  15421. */
  15422. this.state = "";
  15423. /**
  15424. * Gets or sets an object used to store user defined information for the node
  15425. */
  15426. this.metadata = null;
  15427. /**
  15428. * Gets or sets a boolean used to define if the node must be serialized
  15429. */
  15430. this.doNotSerialize = false;
  15431. /** @ignore */
  15432. this._isDisposed = false;
  15433. /**
  15434. * Gets a list of {BABYLON.Animation} associated with the node
  15435. */
  15436. this.animations = new Array();
  15437. this._ranges = {};
  15438. this._isEnabled = true;
  15439. this._isReady = true;
  15440. /** @ignore */
  15441. this._currentRenderId = -1;
  15442. this._parentRenderId = -1;
  15443. this._animationPropertiesOverride = null;
  15444. /**
  15445. * An event triggered when the mesh is disposed
  15446. * @type {BABYLON.Observable}
  15447. */
  15448. this.onDisposeObservable = new BABYLON.Observable();
  15449. // Behaviors
  15450. this._behaviors = new Array();
  15451. this.name = name;
  15452. this.id = name;
  15453. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15454. this.uniqueId = this._scene.getUniqueId();
  15455. this._initCache();
  15456. }
  15457. /**
  15458. * Gets a boolean indicating if the node has been disposed
  15459. * @returns true if the node was disposed
  15460. */
  15461. Node.prototype.isDisposed = function () {
  15462. return this._isDisposed;
  15463. };
  15464. Object.defineProperty(Node.prototype, "parent", {
  15465. get: function () {
  15466. return this._parentNode;
  15467. },
  15468. /**
  15469. * Gets or sets the parent of the node
  15470. */
  15471. set: function (parent) {
  15472. if (this._parentNode === parent) {
  15473. return;
  15474. }
  15475. // Remove self from list of children of parent
  15476. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15477. var index = this._parentNode._children.indexOf(this);
  15478. if (index !== -1) {
  15479. this._parentNode._children.splice(index, 1);
  15480. }
  15481. }
  15482. // Store new parent
  15483. this._parentNode = parent;
  15484. // Add as child to new parent
  15485. if (this._parentNode) {
  15486. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15487. this._parentNode._children = new Array();
  15488. }
  15489. this._parentNode._children.push(this);
  15490. }
  15491. },
  15492. enumerable: true,
  15493. configurable: true
  15494. });
  15495. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15496. /**
  15497. * Gets or sets the animation properties override
  15498. */
  15499. get: function () {
  15500. return this._animationPropertiesOverride;
  15501. },
  15502. set: function (value) {
  15503. this._animationPropertiesOverride = value;
  15504. },
  15505. enumerable: true,
  15506. configurable: true
  15507. });
  15508. /**
  15509. * Gets a string idenfifying the name of the class
  15510. * @returns "Node" string
  15511. */
  15512. Node.prototype.getClassName = function () {
  15513. return "Node";
  15514. };
  15515. Object.defineProperty(Node.prototype, "onDispose", {
  15516. /**
  15517. * Sets a callback that will be raised when the node will be disposed
  15518. */
  15519. set: function (callback) {
  15520. if (this._onDisposeObserver) {
  15521. this.onDisposeObservable.remove(this._onDisposeObserver);
  15522. }
  15523. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15524. },
  15525. enumerable: true,
  15526. configurable: true
  15527. });
  15528. /**
  15529. * Gets the scene of the node
  15530. * @returns a {BABYLON.Scene}
  15531. */
  15532. Node.prototype.getScene = function () {
  15533. return this._scene;
  15534. };
  15535. /**
  15536. * Gets the engine of the node
  15537. * @returns a {BABYLON.Engine}
  15538. */
  15539. Node.prototype.getEngine = function () {
  15540. return this._scene.getEngine();
  15541. };
  15542. /**
  15543. * Attach a behavior to the node
  15544. * @see http://doc.babylonjs.com/features/behaviour
  15545. * @param behavior defines the behavior to attach
  15546. * @returns the current Node
  15547. */
  15548. Node.prototype.addBehavior = function (behavior) {
  15549. var _this = this;
  15550. var index = this._behaviors.indexOf(behavior);
  15551. if (index !== -1) {
  15552. return this;
  15553. }
  15554. behavior.init();
  15555. if (this._scene.isLoading) {
  15556. // We defer the attach when the scene will be loaded
  15557. var observer = this._scene.onDataLoadedObservable.add(function () {
  15558. behavior.attach(_this);
  15559. setTimeout(function () {
  15560. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15561. _this._scene.onDataLoadedObservable.remove(observer);
  15562. }, 0);
  15563. });
  15564. }
  15565. else {
  15566. behavior.attach(this);
  15567. }
  15568. this._behaviors.push(behavior);
  15569. return this;
  15570. };
  15571. /**
  15572. * Remove an attached behavior
  15573. * @see http://doc.babylonjs.com/features/behaviour
  15574. * @param behavior defines the behavior to attach
  15575. * @returns the current Node
  15576. */
  15577. Node.prototype.removeBehavior = function (behavior) {
  15578. var index = this._behaviors.indexOf(behavior);
  15579. if (index === -1) {
  15580. return this;
  15581. }
  15582. this._behaviors[index].detach();
  15583. this._behaviors.splice(index, 1);
  15584. return this;
  15585. };
  15586. Object.defineProperty(Node.prototype, "behaviors", {
  15587. /**
  15588. * Gets the list of attached behaviors
  15589. * @see http://doc.babylonjs.com/features/behaviour
  15590. */
  15591. get: function () {
  15592. return this._behaviors;
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. /**
  15598. * Gets an attached behavior by name
  15599. * @param name defines the name of the behavior to look for
  15600. * @see http://doc.babylonjs.com/features/behaviour
  15601. * @returns null if behavior was not found else the requested behavior
  15602. */
  15603. Node.prototype.getBehaviorByName = function (name) {
  15604. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15605. var behavior = _a[_i];
  15606. if (behavior.name === name) {
  15607. return behavior;
  15608. }
  15609. }
  15610. return null;
  15611. };
  15612. /**
  15613. * Returns the world matrix of the node
  15614. * @returns a matrix containing the node's world matrix
  15615. */
  15616. Node.prototype.getWorldMatrix = function () {
  15617. return BABYLON.Matrix.Identity();
  15618. };
  15619. // override it in derived class if you add new variables to the cache
  15620. // and call the parent class method
  15621. /** @ignore */
  15622. Node.prototype._initCache = function () {
  15623. this._cache = {};
  15624. this._cache.parent = undefined;
  15625. };
  15626. /** @ignore */
  15627. Node.prototype.updateCache = function (force) {
  15628. if (!force && this.isSynchronized())
  15629. return;
  15630. this._cache.parent = this.parent;
  15631. this._updateCache();
  15632. };
  15633. // override it in derived class if you add new variables to the cache
  15634. // and call the parent class method if !ignoreParentClass
  15635. /** @ignore */
  15636. Node.prototype._updateCache = function (ignoreParentClass) {
  15637. };
  15638. // override it in derived class if you add new variables to the cache
  15639. /** @ignore */
  15640. Node.prototype._isSynchronized = function () {
  15641. return true;
  15642. };
  15643. /** @ignore */
  15644. Node.prototype._markSyncedWithParent = function () {
  15645. if (this.parent) {
  15646. this._parentRenderId = this.parent._currentRenderId;
  15647. }
  15648. };
  15649. /** @ignore */
  15650. Node.prototype.isSynchronizedWithParent = function () {
  15651. if (!this.parent) {
  15652. return true;
  15653. }
  15654. if (this._parentRenderId !== this.parent._currentRenderId) {
  15655. return false;
  15656. }
  15657. return this.parent.isSynchronized();
  15658. };
  15659. /** @ignore */
  15660. Node.prototype.isSynchronized = function (updateCache) {
  15661. var check = this.hasNewParent();
  15662. check = check || !this.isSynchronizedWithParent();
  15663. check = check || !this._isSynchronized();
  15664. if (updateCache)
  15665. this.updateCache(true);
  15666. return !check;
  15667. };
  15668. /** @ignore */
  15669. Node.prototype.hasNewParent = function (update) {
  15670. if (this._cache.parent === this.parent)
  15671. return false;
  15672. if (update)
  15673. this._cache.parent = this.parent;
  15674. return true;
  15675. };
  15676. /**
  15677. * Is this node ready to be used/rendered
  15678. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15679. * @return true if the node is ready
  15680. */
  15681. Node.prototype.isReady = function (completeCheck) {
  15682. if (completeCheck === void 0) { completeCheck = false; }
  15683. return this._isReady;
  15684. };
  15685. /**
  15686. * Is this node enabled?
  15687. * 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
  15688. * @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
  15689. * @return whether this node (and its parent) is enabled
  15690. * @see setEnabled
  15691. */
  15692. Node.prototype.isEnabled = function (checkAncestors) {
  15693. if (checkAncestors === void 0) { checkAncestors = true; }
  15694. if (checkAncestors === false) {
  15695. return this._isEnabled;
  15696. }
  15697. if (this._isEnabled === false) {
  15698. return false;
  15699. }
  15700. if (this.parent !== undefined && this.parent !== null) {
  15701. return this.parent.isEnabled(checkAncestors);
  15702. }
  15703. return true;
  15704. };
  15705. /**
  15706. * Set the enabled state of this node
  15707. * @param value defines the new enabled state
  15708. * @see isEnabled
  15709. */
  15710. Node.prototype.setEnabled = function (value) {
  15711. this._isEnabled = value;
  15712. };
  15713. /**
  15714. * Is this node a descendant of the given node?
  15715. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15716. * @param ancestor defines the parent node to inspect
  15717. * @see parent
  15718. * @returns a boolean indicating if this node is a descendant of the given node
  15719. */
  15720. Node.prototype.isDescendantOf = function (ancestor) {
  15721. if (this.parent) {
  15722. if (this.parent === ancestor) {
  15723. return true;
  15724. }
  15725. return this.parent.isDescendantOf(ancestor);
  15726. }
  15727. return false;
  15728. };
  15729. /** @ignore */
  15730. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15731. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15732. if (!this._children) {
  15733. return;
  15734. }
  15735. for (var index = 0; index < this._children.length; index++) {
  15736. var item = this._children[index];
  15737. if (!predicate || predicate(item)) {
  15738. results.push(item);
  15739. }
  15740. if (!directDescendantsOnly) {
  15741. item._getDescendants(results, false, predicate);
  15742. }
  15743. }
  15744. };
  15745. /**
  15746. * Will return all nodes that have this node as ascendant
  15747. * @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
  15748. * @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
  15749. * @return all children nodes of all types
  15750. */
  15751. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15752. var results = new Array();
  15753. this._getDescendants(results, directDescendantsOnly, predicate);
  15754. return results;
  15755. };
  15756. /**
  15757. * Get all child-meshes of this node
  15758. * @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
  15759. * @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
  15760. * @returns an array of {BABYLON.AbstractMesh}
  15761. */
  15762. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15763. var results = [];
  15764. this._getDescendants(results, directDescendantsOnly, function (node) {
  15765. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15766. });
  15767. return results;
  15768. };
  15769. /**
  15770. * Get all child-transformNodes of this node
  15771. * @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
  15772. * @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
  15773. * @returns an array of {BABYLON.TransformNode}
  15774. */
  15775. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15776. var results = [];
  15777. this._getDescendants(results, directDescendantsOnly, function (node) {
  15778. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15779. });
  15780. return results;
  15781. };
  15782. /**
  15783. * Get all direct children of this node
  15784. * @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
  15785. * @returns an array of {BABYLON.Node}
  15786. */
  15787. Node.prototype.getChildren = function (predicate) {
  15788. return this.getDescendants(true, predicate);
  15789. };
  15790. /** @ignore */
  15791. Node.prototype._setReady = function (state) {
  15792. if (state === this._isReady) {
  15793. return;
  15794. }
  15795. if (!state) {
  15796. this._isReady = false;
  15797. return;
  15798. }
  15799. this._isReady = true;
  15800. if (this.onReady) {
  15801. this.onReady(this);
  15802. }
  15803. };
  15804. /**
  15805. * Get an animation by name
  15806. * @param name defines the name of the animation to look for
  15807. * @returns null if not found else the requested animation
  15808. */
  15809. Node.prototype.getAnimationByName = function (name) {
  15810. for (var i = 0; i < this.animations.length; i++) {
  15811. var animation = this.animations[i];
  15812. if (animation.name === name) {
  15813. return animation;
  15814. }
  15815. }
  15816. return null;
  15817. };
  15818. /**
  15819. * Creates an animation range for this node
  15820. * @param name defines the name of the range
  15821. * @param from defines the starting key
  15822. * @param to defines the end key
  15823. */
  15824. Node.prototype.createAnimationRange = function (name, from, to) {
  15825. // check name not already in use
  15826. if (!this._ranges[name]) {
  15827. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15828. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15829. if (this.animations[i]) {
  15830. this.animations[i].createRange(name, from, to);
  15831. }
  15832. }
  15833. }
  15834. };
  15835. /**
  15836. * Delete a specific animation range
  15837. * @param name defines the name of the range to delete
  15838. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15839. */
  15840. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15841. if (deleteFrames === void 0) { deleteFrames = true; }
  15842. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15843. if (this.animations[i]) {
  15844. this.animations[i].deleteRange(name, deleteFrames);
  15845. }
  15846. }
  15847. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15848. };
  15849. /**
  15850. * Get an animation range by name
  15851. * @param name defines the name of the animation range to look for
  15852. * @returns null if not found else the requested animation range
  15853. */
  15854. Node.prototype.getAnimationRange = function (name) {
  15855. return this._ranges[name];
  15856. };
  15857. /**
  15858. * Will start the animation sequence
  15859. * @param name defines the range frames for animation sequence
  15860. * @param loop defines if the animation should loop (false by default)
  15861. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15862. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15863. * @returns the object created for this animation. If range does not exist, it will return null
  15864. */
  15865. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15866. var range = this.getAnimationRange(name);
  15867. if (!range) {
  15868. return null;
  15869. }
  15870. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15871. };
  15872. /**
  15873. * Serialize animation ranges into a JSON compatible object
  15874. * @returns serialization object
  15875. */
  15876. Node.prototype.serializeAnimationRanges = function () {
  15877. var serializationRanges = [];
  15878. for (var name in this._ranges) {
  15879. var localRange = this._ranges[name];
  15880. if (!localRange) {
  15881. continue;
  15882. }
  15883. var range = {};
  15884. range.name = name;
  15885. range.from = localRange.from;
  15886. range.to = localRange.to;
  15887. serializationRanges.push(range);
  15888. }
  15889. return serializationRanges;
  15890. };
  15891. /**
  15892. * Computes the world matrix of the node
  15893. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15894. * @returns the world matrix
  15895. */
  15896. Node.prototype.computeWorldMatrix = function (force) {
  15897. return BABYLON.Matrix.Identity();
  15898. };
  15899. /**
  15900. * Releases resources associated with this node.
  15901. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15902. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15903. */
  15904. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15905. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15906. if (!doNotRecurse) {
  15907. var nodes = this.getDescendants(true);
  15908. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15909. var node = nodes_1[_i];
  15910. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15911. }
  15912. }
  15913. else {
  15914. var transformNodes = this.getChildTransformNodes(true);
  15915. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15916. var transformNode = transformNodes_1[_a];
  15917. transformNode.parent = null;
  15918. transformNode.computeWorldMatrix(true);
  15919. }
  15920. }
  15921. this.parent = null;
  15922. // Callback
  15923. this.onDisposeObservable.notifyObservers(this);
  15924. this.onDisposeObservable.clear();
  15925. // Behaviors
  15926. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  15927. var behavior = _c[_b];
  15928. behavior.detach();
  15929. }
  15930. this._behaviors = [];
  15931. this._isDisposed = true;
  15932. };
  15933. /**
  15934. * Parse animation range data from a serialization object and store them into a given node
  15935. * @param node defines where to store the animation ranges
  15936. * @param parsedNode defines the serialization object to read data from
  15937. * @param scene defines the hosting scene
  15938. */
  15939. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15940. if (parsedNode.ranges) {
  15941. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15942. var data = parsedNode.ranges[index];
  15943. node.createAnimationRange(data.name, data.from, data.to);
  15944. }
  15945. }
  15946. };
  15947. __decorate([
  15948. BABYLON.serialize()
  15949. ], Node.prototype, "name", void 0);
  15950. __decorate([
  15951. BABYLON.serialize()
  15952. ], Node.prototype, "id", void 0);
  15953. __decorate([
  15954. BABYLON.serialize()
  15955. ], Node.prototype, "uniqueId", void 0);
  15956. __decorate([
  15957. BABYLON.serialize()
  15958. ], Node.prototype, "state", void 0);
  15959. __decorate([
  15960. BABYLON.serialize()
  15961. ], Node.prototype, "metadata", void 0);
  15962. return Node;
  15963. }());
  15964. BABYLON.Node = Node;
  15965. })(BABYLON || (BABYLON = {}));
  15966. //# sourceMappingURL=babylon.node.js.map
  15967. var BABYLON;
  15968. (function (BABYLON) {
  15969. var BoundingSphere = /** @class */ (function () {
  15970. function BoundingSphere(minimum, maximum) {
  15971. this.minimum = minimum;
  15972. this.maximum = maximum;
  15973. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15974. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15975. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15976. this.radius = distance * 0.5;
  15977. this.centerWorld = BABYLON.Vector3.Zero();
  15978. this._update(BABYLON.Matrix.Identity());
  15979. }
  15980. // Methods
  15981. BoundingSphere.prototype._update = function (world) {
  15982. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15983. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15984. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15985. };
  15986. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15987. for (var i = 0; i < 6; i++) {
  15988. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15989. return false;
  15990. }
  15991. return true;
  15992. };
  15993. BoundingSphere.prototype.intersectsPoint = function (point) {
  15994. var x = this.centerWorld.x - point.x;
  15995. var y = this.centerWorld.y - point.y;
  15996. var z = this.centerWorld.z - point.z;
  15997. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15998. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15999. return false;
  16000. return true;
  16001. };
  16002. // Statics
  16003. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16004. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16005. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16006. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16007. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16008. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16009. return false;
  16010. return true;
  16011. };
  16012. return BoundingSphere;
  16013. }());
  16014. BABYLON.BoundingSphere = BoundingSphere;
  16015. })(BABYLON || (BABYLON = {}));
  16016. //# sourceMappingURL=babylon.boundingSphere.js.map
  16017. var BABYLON;
  16018. (function (BABYLON) {
  16019. var BoundingBox = /** @class */ (function () {
  16020. function BoundingBox(minimum, maximum) {
  16021. this.minimum = minimum;
  16022. this.maximum = maximum;
  16023. this.vectors = new Array();
  16024. this.vectorsWorld = new Array();
  16025. // Bounding vectors
  16026. this.vectors.push(this.minimum.clone());
  16027. this.vectors.push(this.maximum.clone());
  16028. this.vectors.push(this.minimum.clone());
  16029. this.vectors[2].x = this.maximum.x;
  16030. this.vectors.push(this.minimum.clone());
  16031. this.vectors[3].y = this.maximum.y;
  16032. this.vectors.push(this.minimum.clone());
  16033. this.vectors[4].z = this.maximum.z;
  16034. this.vectors.push(this.maximum.clone());
  16035. this.vectors[5].z = this.minimum.z;
  16036. this.vectors.push(this.maximum.clone());
  16037. this.vectors[6].x = this.minimum.x;
  16038. this.vectors.push(this.maximum.clone());
  16039. this.vectors[7].y = this.minimum.y;
  16040. // OBB
  16041. this.center = this.maximum.add(this.minimum).scale(0.5);
  16042. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16043. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16044. // World
  16045. for (var index = 0; index < this.vectors.length; index++) {
  16046. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16047. }
  16048. this.minimumWorld = BABYLON.Vector3.Zero();
  16049. this.maximumWorld = BABYLON.Vector3.Zero();
  16050. this.centerWorld = BABYLON.Vector3.Zero();
  16051. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16052. this._update(BABYLON.Matrix.Identity());
  16053. }
  16054. // Methods
  16055. BoundingBox.prototype.getWorldMatrix = function () {
  16056. return this._worldMatrix;
  16057. };
  16058. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16059. this._worldMatrix.copyFrom(matrix);
  16060. return this;
  16061. };
  16062. BoundingBox.prototype._update = function (world) {
  16063. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16064. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16065. for (var index = 0; index < this.vectors.length; index++) {
  16066. var v = this.vectorsWorld[index];
  16067. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16068. if (v.x < this.minimumWorld.x)
  16069. this.minimumWorld.x = v.x;
  16070. if (v.y < this.minimumWorld.y)
  16071. this.minimumWorld.y = v.y;
  16072. if (v.z < this.minimumWorld.z)
  16073. this.minimumWorld.z = v.z;
  16074. if (v.x > this.maximumWorld.x)
  16075. this.maximumWorld.x = v.x;
  16076. if (v.y > this.maximumWorld.y)
  16077. this.maximumWorld.y = v.y;
  16078. if (v.z > this.maximumWorld.z)
  16079. this.maximumWorld.z = v.z;
  16080. }
  16081. // Extend
  16082. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16083. this.extendSizeWorld.scaleInPlace(0.5);
  16084. // OBB
  16085. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16086. this.centerWorld.scaleInPlace(0.5);
  16087. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16088. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16089. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16090. this._worldMatrix = world;
  16091. };
  16092. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16093. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16094. };
  16095. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16096. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16097. };
  16098. BoundingBox.prototype.intersectsPoint = function (point) {
  16099. var delta = -BABYLON.Epsilon;
  16100. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16101. return false;
  16102. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16103. return false;
  16104. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16105. return false;
  16106. return true;
  16107. };
  16108. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16109. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16110. };
  16111. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16112. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16113. return false;
  16114. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16115. return false;
  16116. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16117. return false;
  16118. return true;
  16119. };
  16120. // Statics
  16121. BoundingBox.Intersects = function (box0, box1) {
  16122. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16123. return false;
  16124. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16125. return false;
  16126. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16127. return false;
  16128. return true;
  16129. };
  16130. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16131. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16132. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16133. return (num <= (sphereRadius * sphereRadius));
  16134. };
  16135. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16136. for (var p = 0; p < 6; p++) {
  16137. for (var i = 0; i < 8; i++) {
  16138. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16139. return false;
  16140. }
  16141. }
  16142. }
  16143. return true;
  16144. };
  16145. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16146. for (var p = 0; p < 6; p++) {
  16147. var inCount = 8;
  16148. for (var i = 0; i < 8; i++) {
  16149. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16150. --inCount;
  16151. }
  16152. else {
  16153. break;
  16154. }
  16155. }
  16156. if (inCount === 0)
  16157. return false;
  16158. }
  16159. return true;
  16160. };
  16161. return BoundingBox;
  16162. }());
  16163. BABYLON.BoundingBox = BoundingBox;
  16164. })(BABYLON || (BABYLON = {}));
  16165. //# sourceMappingURL=babylon.boundingBox.js.map
  16166. var BABYLON;
  16167. (function (BABYLON) {
  16168. var computeBoxExtents = function (axis, box) {
  16169. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16170. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16171. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16172. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16173. var r = r0 + r1 + r2;
  16174. return {
  16175. min: p - r,
  16176. max: p + r
  16177. };
  16178. };
  16179. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16180. var axisOverlap = function (axis, box0, box1) {
  16181. var result0 = computeBoxExtents(axis, box0);
  16182. var result1 = computeBoxExtents(axis, box1);
  16183. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16184. };
  16185. var BoundingInfo = /** @class */ (function () {
  16186. function BoundingInfo(minimum, maximum) {
  16187. this.minimum = minimum;
  16188. this.maximum = maximum;
  16189. this._isLocked = false;
  16190. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16191. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16192. }
  16193. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16194. get: function () {
  16195. return this._isLocked;
  16196. },
  16197. set: function (value) {
  16198. this._isLocked = value;
  16199. },
  16200. enumerable: true,
  16201. configurable: true
  16202. });
  16203. // Methods
  16204. BoundingInfo.prototype.update = function (world) {
  16205. if (this._isLocked) {
  16206. return;
  16207. }
  16208. this.boundingBox._update(world);
  16209. this.boundingSphere._update(world);
  16210. };
  16211. /**
  16212. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16213. * @param center New center of the bounding info
  16214. * @param extend New extend of the bounding info
  16215. */
  16216. BoundingInfo.prototype.centerOn = function (center, extend) {
  16217. this.minimum = center.subtract(extend);
  16218. this.maximum = center.add(extend);
  16219. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16220. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16221. return this;
  16222. };
  16223. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16224. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16225. return false;
  16226. return this.boundingBox.isInFrustum(frustumPlanes);
  16227. };
  16228. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16229. /**
  16230. * Gets the world distance between the min and max points of the bounding box
  16231. */
  16232. get: function () {
  16233. var boundingBox = this.boundingBox;
  16234. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16235. return size.length();
  16236. },
  16237. enumerable: true,
  16238. configurable: true
  16239. });
  16240. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16241. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16242. };
  16243. BoundingInfo.prototype._checkCollision = function (collider) {
  16244. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16245. };
  16246. BoundingInfo.prototype.intersectsPoint = function (point) {
  16247. if (!this.boundingSphere.centerWorld) {
  16248. return false;
  16249. }
  16250. if (!this.boundingSphere.intersectsPoint(point)) {
  16251. return false;
  16252. }
  16253. if (!this.boundingBox.intersectsPoint(point)) {
  16254. return false;
  16255. }
  16256. return true;
  16257. };
  16258. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16259. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16260. return false;
  16261. }
  16262. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16263. return false;
  16264. }
  16265. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16266. return false;
  16267. }
  16268. if (!precise) {
  16269. return true;
  16270. }
  16271. var box0 = this.boundingBox;
  16272. var box1 = boundingInfo.boundingBox;
  16273. if (!axisOverlap(box0.directions[0], box0, box1))
  16274. return false;
  16275. if (!axisOverlap(box0.directions[1], box0, box1))
  16276. return false;
  16277. if (!axisOverlap(box0.directions[2], box0, box1))
  16278. return false;
  16279. if (!axisOverlap(box1.directions[0], box0, box1))
  16280. return false;
  16281. if (!axisOverlap(box1.directions[1], box0, box1))
  16282. return false;
  16283. if (!axisOverlap(box1.directions[2], box0, box1))
  16284. return false;
  16285. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16286. return false;
  16287. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16288. return false;
  16289. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16290. return false;
  16291. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16292. return false;
  16293. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16294. return false;
  16295. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16296. return false;
  16297. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16298. return false;
  16299. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16300. return false;
  16301. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16302. return false;
  16303. return true;
  16304. };
  16305. return BoundingInfo;
  16306. }());
  16307. BABYLON.BoundingInfo = BoundingInfo;
  16308. })(BABYLON || (BABYLON = {}));
  16309. //# sourceMappingURL=babylon.boundingInfo.js.map
  16310. var BABYLON;
  16311. (function (BABYLON) {
  16312. var TransformNode = /** @class */ (function (_super) {
  16313. __extends(TransformNode, _super);
  16314. function TransformNode(name, scene, isPure) {
  16315. if (scene === void 0) { scene = null; }
  16316. if (isPure === void 0) { isPure = true; }
  16317. var _this = _super.call(this, name, scene) || this;
  16318. // Properties
  16319. _this._rotation = BABYLON.Vector3.Zero();
  16320. _this._scaling = BABYLON.Vector3.One();
  16321. _this._isDirty = false;
  16322. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16323. _this.scalingDeterminant = 1;
  16324. _this.infiniteDistance = false;
  16325. _this.position = BABYLON.Vector3.Zero();
  16326. _this._localWorld = BABYLON.Matrix.Zero();
  16327. _this._worldMatrix = BABYLON.Matrix.Zero();
  16328. _this._worldMatrixDeterminant = 0;
  16329. _this._absolutePosition = BABYLON.Vector3.Zero();
  16330. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16331. _this._postMultiplyPivotMatrix = false;
  16332. _this._isWorldMatrixFrozen = false;
  16333. /**
  16334. * An event triggered after the world matrix is updated
  16335. * @type {BABYLON.Observable}
  16336. */
  16337. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16338. _this._nonUniformScaling = false;
  16339. if (isPure) {
  16340. _this.getScene().addTransformNode(_this);
  16341. }
  16342. return _this;
  16343. }
  16344. /**
  16345. * Gets a string idenfifying the name of the class
  16346. * @returns "TransformNode" string
  16347. */
  16348. TransformNode.prototype.getClassName = function () {
  16349. return "TransformNode";
  16350. };
  16351. Object.defineProperty(TransformNode.prototype, "rotation", {
  16352. /**
  16353. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16354. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16355. * Default : (0.0, 0.0, 0.0)
  16356. */
  16357. get: function () {
  16358. return this._rotation;
  16359. },
  16360. set: function (newRotation) {
  16361. this._rotation = newRotation;
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. Object.defineProperty(TransformNode.prototype, "scaling", {
  16367. /**
  16368. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16369. * Default : (1.0, 1.0, 1.0)
  16370. */
  16371. get: function () {
  16372. return this._scaling;
  16373. },
  16374. /**
  16375. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16376. * Default : (1.0, 1.0, 1.0)
  16377. */
  16378. set: function (newScaling) {
  16379. this._scaling = newScaling;
  16380. },
  16381. enumerable: true,
  16382. configurable: true
  16383. });
  16384. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16385. /**
  16386. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16387. * It's null by default.
  16388. * 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)
  16389. */
  16390. get: function () {
  16391. return this._rotationQuaternion;
  16392. },
  16393. set: function (quaternion) {
  16394. this._rotationQuaternion = quaternion;
  16395. //reset the rotation vector.
  16396. if (quaternion && this.rotation.length()) {
  16397. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16398. }
  16399. },
  16400. enumerable: true,
  16401. configurable: true
  16402. });
  16403. /**
  16404. * Returns the latest update of the World matrix
  16405. * Returns a Matrix.
  16406. */
  16407. TransformNode.prototype.getWorldMatrix = function () {
  16408. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16409. this.computeWorldMatrix();
  16410. }
  16411. return this._worldMatrix;
  16412. };
  16413. /**
  16414. * Returns the latest update of the World matrix determinant.
  16415. */
  16416. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16417. return this._worldMatrixDeterminant;
  16418. };
  16419. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16420. /**
  16421. * Returns directly the latest state of the mesh World matrix.
  16422. * A Matrix is returned.
  16423. */
  16424. get: function () {
  16425. return this._worldMatrix;
  16426. },
  16427. enumerable: true,
  16428. configurable: true
  16429. });
  16430. /**
  16431. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16432. * Returns the AbstractMesh.
  16433. */
  16434. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16435. this._poseMatrix.copyFrom(matrix);
  16436. return this;
  16437. };
  16438. /**
  16439. * Returns the mesh Pose matrix.
  16440. * Returned object : Matrix
  16441. */
  16442. TransformNode.prototype.getPoseMatrix = function () {
  16443. return this._poseMatrix;
  16444. };
  16445. TransformNode.prototype._isSynchronized = function () {
  16446. if (this._isDirty) {
  16447. return false;
  16448. }
  16449. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16450. return false;
  16451. if (this._cache.pivotMatrixUpdated) {
  16452. return false;
  16453. }
  16454. if (this.infiniteDistance) {
  16455. return false;
  16456. }
  16457. if (!this._cache.position.equals(this.position))
  16458. return false;
  16459. if (this.rotationQuaternion) {
  16460. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16461. return false;
  16462. }
  16463. if (!this._cache.rotation.equals(this.rotation))
  16464. return false;
  16465. if (!this._cache.scaling.equals(this.scaling))
  16466. return false;
  16467. return true;
  16468. };
  16469. TransformNode.prototype._initCache = function () {
  16470. _super.prototype._initCache.call(this);
  16471. this._cache.localMatrixUpdated = false;
  16472. this._cache.position = BABYLON.Vector3.Zero();
  16473. this._cache.scaling = BABYLON.Vector3.Zero();
  16474. this._cache.rotation = BABYLON.Vector3.Zero();
  16475. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16476. this._cache.billboardMode = -1;
  16477. };
  16478. TransformNode.prototype.markAsDirty = function (property) {
  16479. if (property === "rotation") {
  16480. this.rotationQuaternion = null;
  16481. }
  16482. this._currentRenderId = Number.MAX_VALUE;
  16483. this._isDirty = true;
  16484. return this;
  16485. };
  16486. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16487. /**
  16488. * Returns the current mesh absolute position.
  16489. * Retuns a Vector3.
  16490. */
  16491. get: function () {
  16492. return this._absolutePosition;
  16493. },
  16494. enumerable: true,
  16495. configurable: true
  16496. });
  16497. /**
  16498. * Sets a new matrix to apply before all other transformation
  16499. * @param matrix defines the transform matrix
  16500. * @returns the current TransformNode
  16501. */
  16502. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16503. return this.setPivotMatrix(matrix, false);
  16504. };
  16505. /**
  16506. * Sets a new pivot matrix to the current node
  16507. * @param matrix defines the new pivot matrix to use
  16508. * @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
  16509. * @returns the current TransformNode
  16510. */
  16511. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16512. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16513. this._pivotMatrix = matrix.clone();
  16514. this._cache.pivotMatrixUpdated = true;
  16515. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16516. if (this._postMultiplyPivotMatrix) {
  16517. if (!this._pivotMatrixInverse) {
  16518. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16519. }
  16520. else {
  16521. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16522. }
  16523. }
  16524. return this;
  16525. };
  16526. /**
  16527. * Returns the mesh pivot matrix.
  16528. * Default : Identity.
  16529. * A Matrix is returned.
  16530. */
  16531. TransformNode.prototype.getPivotMatrix = function () {
  16532. return this._pivotMatrix;
  16533. };
  16534. /**
  16535. * Prevents the World matrix to be computed any longer.
  16536. * Returns the AbstractMesh.
  16537. */
  16538. TransformNode.prototype.freezeWorldMatrix = function () {
  16539. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16540. this.computeWorldMatrix(true);
  16541. this._isWorldMatrixFrozen = true;
  16542. return this;
  16543. };
  16544. /**
  16545. * Allows back the World matrix computation.
  16546. * Returns the AbstractMesh.
  16547. */
  16548. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16549. this._isWorldMatrixFrozen = false;
  16550. this.computeWorldMatrix(true);
  16551. return this;
  16552. };
  16553. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16554. /**
  16555. * True if the World matrix has been frozen.
  16556. * Returns a boolean.
  16557. */
  16558. get: function () {
  16559. return this._isWorldMatrixFrozen;
  16560. },
  16561. enumerable: true,
  16562. configurable: true
  16563. });
  16564. /**
  16565. * Retuns the mesh absolute position in the World.
  16566. * Returns a Vector3.
  16567. */
  16568. TransformNode.prototype.getAbsolutePosition = function () {
  16569. this.computeWorldMatrix();
  16570. return this._absolutePosition;
  16571. };
  16572. /**
  16573. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16574. * Returns the AbstractMesh.
  16575. */
  16576. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16577. if (!absolutePosition) {
  16578. return this;
  16579. }
  16580. var absolutePositionX;
  16581. var absolutePositionY;
  16582. var absolutePositionZ;
  16583. if (absolutePosition.x === undefined) {
  16584. if (arguments.length < 3) {
  16585. return this;
  16586. }
  16587. absolutePositionX = arguments[0];
  16588. absolutePositionY = arguments[1];
  16589. absolutePositionZ = arguments[2];
  16590. }
  16591. else {
  16592. absolutePositionX = absolutePosition.x;
  16593. absolutePositionY = absolutePosition.y;
  16594. absolutePositionZ = absolutePosition.z;
  16595. }
  16596. if (this.parent) {
  16597. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16598. invertParentWorldMatrix.invert();
  16599. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16600. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16601. }
  16602. else {
  16603. this.position.x = absolutePositionX;
  16604. this.position.y = absolutePositionY;
  16605. this.position.z = absolutePositionZ;
  16606. }
  16607. return this;
  16608. };
  16609. /**
  16610. * Sets the mesh position in its local space.
  16611. * Returns the AbstractMesh.
  16612. */
  16613. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16614. this.computeWorldMatrix();
  16615. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16616. return this;
  16617. };
  16618. /**
  16619. * Returns the mesh position in the local space from the current World matrix values.
  16620. * Returns a new Vector3.
  16621. */
  16622. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16623. this.computeWorldMatrix();
  16624. var invLocalWorldMatrix = this._localWorld.clone();
  16625. invLocalWorldMatrix.invert();
  16626. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16627. };
  16628. /**
  16629. * Translates the mesh along the passed Vector3 in its local space.
  16630. * Returns the AbstractMesh.
  16631. */
  16632. TransformNode.prototype.locallyTranslate = function (vector3) {
  16633. this.computeWorldMatrix(true);
  16634. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16635. return this;
  16636. };
  16637. /**
  16638. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16639. * @param targetPoint the position (must be in same space as current mesh) to look at
  16640. * @param yawCor optional yaw (y-axis) correction in radians
  16641. * @param pitchCor optional pitch (x-axis) correction in radians
  16642. * @param rollCor optional roll (z-axis) correction in radians
  16643. * @param space the choosen space of the target
  16644. * @returns the TransformNode.
  16645. */
  16646. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16647. if (yawCor === void 0) { yawCor = 0; }
  16648. if (pitchCor === void 0) { pitchCor = 0; }
  16649. if (rollCor === void 0) { rollCor = 0; }
  16650. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16651. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16652. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16653. targetPoint.subtractToRef(pos, dv);
  16654. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16655. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16656. var pitch = Math.atan2(dv.y, len);
  16657. if (this.rotationQuaternion) {
  16658. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16659. }
  16660. else {
  16661. this.rotation.x = pitch + pitchCor;
  16662. this.rotation.y = yaw + yawCor;
  16663. this.rotation.z = rollCor;
  16664. }
  16665. return this;
  16666. };
  16667. /**
  16668. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16669. * This Vector3 is expressed in the World space.
  16670. */
  16671. TransformNode.prototype.getDirection = function (localAxis) {
  16672. var result = BABYLON.Vector3.Zero();
  16673. this.getDirectionToRef(localAxis, result);
  16674. return result;
  16675. };
  16676. /**
  16677. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16678. * localAxis is expressed in the mesh local space.
  16679. * result is computed in the Wordl space from the mesh World matrix.
  16680. * Returns the AbstractMesh.
  16681. */
  16682. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16683. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16684. return this;
  16685. };
  16686. /**
  16687. * Sets a new pivot point to the current node
  16688. * @param point defines the new pivot point to use
  16689. * @param space defines if the point is in world or local space (local by default)
  16690. * @returns the current TransformNode
  16691. */
  16692. TransformNode.prototype.setPivotPoint = function (point, space) {
  16693. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16694. if (this.getScene().getRenderId() == 0) {
  16695. this.computeWorldMatrix(true);
  16696. }
  16697. var wm = this.getWorldMatrix();
  16698. if (space == BABYLON.Space.WORLD) {
  16699. var tmat = BABYLON.Tmp.Matrix[0];
  16700. wm.invertToRef(tmat);
  16701. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16702. }
  16703. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16704. };
  16705. /**
  16706. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16707. */
  16708. TransformNode.prototype.getPivotPoint = function () {
  16709. var point = BABYLON.Vector3.Zero();
  16710. this.getPivotPointToRef(point);
  16711. return point;
  16712. };
  16713. /**
  16714. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16715. * Returns the AbstractMesh.
  16716. */
  16717. TransformNode.prototype.getPivotPointToRef = function (result) {
  16718. result.x = -this._pivotMatrix.m[12];
  16719. result.y = -this._pivotMatrix.m[13];
  16720. result.z = -this._pivotMatrix.m[14];
  16721. return this;
  16722. };
  16723. /**
  16724. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16725. */
  16726. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16727. var point = BABYLON.Vector3.Zero();
  16728. this.getAbsolutePivotPointToRef(point);
  16729. return point;
  16730. };
  16731. /**
  16732. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16733. * Returns the AbstractMesh.
  16734. */
  16735. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16736. result.x = this._pivotMatrix.m[12];
  16737. result.y = this._pivotMatrix.m[13];
  16738. result.z = this._pivotMatrix.m[14];
  16739. this.getPivotPointToRef(result);
  16740. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16741. return this;
  16742. };
  16743. /**
  16744. * Defines the passed node as the parent of the current node.
  16745. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16746. * Returns the TransformNode.
  16747. */
  16748. TransformNode.prototype.setParent = function (node) {
  16749. if (node === null) {
  16750. var rotation = BABYLON.Tmp.Quaternion[0];
  16751. var position = BABYLON.Tmp.Vector3[0];
  16752. var scale = BABYLON.Tmp.Vector3[1];
  16753. if (this.parent && this.parent.computeWorldMatrix) {
  16754. this.parent.computeWorldMatrix(true);
  16755. }
  16756. this.computeWorldMatrix(true);
  16757. this.getWorldMatrix().decompose(scale, rotation, position);
  16758. if (this.rotationQuaternion) {
  16759. this.rotationQuaternion.copyFrom(rotation);
  16760. }
  16761. else {
  16762. rotation.toEulerAnglesToRef(this.rotation);
  16763. }
  16764. this.scaling.x = scale.x;
  16765. this.scaling.y = scale.y;
  16766. this.scaling.z = scale.z;
  16767. this.position.x = position.x;
  16768. this.position.y = position.y;
  16769. this.position.z = position.z;
  16770. }
  16771. else {
  16772. var rotation = BABYLON.Tmp.Quaternion[0];
  16773. var position = BABYLON.Tmp.Vector3[0];
  16774. var scale = BABYLON.Tmp.Vector3[1];
  16775. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16776. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16777. this.computeWorldMatrix(true);
  16778. node.computeWorldMatrix(true);
  16779. node.getWorldMatrix().invertToRef(invParentMatrix);
  16780. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16781. diffMatrix.decompose(scale, rotation, position);
  16782. if (this.rotationQuaternion) {
  16783. this.rotationQuaternion.copyFrom(rotation);
  16784. }
  16785. else {
  16786. rotation.toEulerAnglesToRef(this.rotation);
  16787. }
  16788. this.position.x = position.x;
  16789. this.position.y = position.y;
  16790. this.position.z = position.z;
  16791. this.scaling.x = scale.x;
  16792. this.scaling.y = scale.y;
  16793. this.scaling.z = scale.z;
  16794. }
  16795. this.parent = node;
  16796. return this;
  16797. };
  16798. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16799. get: function () {
  16800. return this._nonUniformScaling;
  16801. },
  16802. enumerable: true,
  16803. configurable: true
  16804. });
  16805. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16806. if (this._nonUniformScaling === value) {
  16807. return false;
  16808. }
  16809. this._nonUniformScaling = true;
  16810. return true;
  16811. };
  16812. /**
  16813. * Attach the current TransformNode to another TransformNode associated with a bone
  16814. * @param bone Bone affecting the TransformNode
  16815. * @param affectedTransformNode TransformNode associated with the bone
  16816. */
  16817. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16818. this._transformToBoneReferal = affectedTransformNode;
  16819. this.parent = bone;
  16820. if (bone.getWorldMatrix().determinant() < 0) {
  16821. this.scalingDeterminant *= -1;
  16822. }
  16823. return this;
  16824. };
  16825. TransformNode.prototype.detachFromBone = function () {
  16826. if (!this.parent) {
  16827. return this;
  16828. }
  16829. if (this.parent.getWorldMatrix().determinant() < 0) {
  16830. this.scalingDeterminant *= -1;
  16831. }
  16832. this._transformToBoneReferal = null;
  16833. this.parent = null;
  16834. return this;
  16835. };
  16836. /**
  16837. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16838. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16839. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16840. * The passed axis is also normalized.
  16841. * Returns the AbstractMesh.
  16842. */
  16843. TransformNode.prototype.rotate = function (axis, amount, space) {
  16844. axis.normalize();
  16845. if (!this.rotationQuaternion) {
  16846. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16847. this.rotation = BABYLON.Vector3.Zero();
  16848. }
  16849. var rotationQuaternion;
  16850. if (!space || space === BABYLON.Space.LOCAL) {
  16851. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16852. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16853. }
  16854. else {
  16855. if (this.parent) {
  16856. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16857. invertParentWorldMatrix.invert();
  16858. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16859. }
  16860. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16861. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16862. }
  16863. return this;
  16864. };
  16865. /**
  16866. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16867. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16868. * The passed axis is also normalized.
  16869. * Returns the AbstractMesh.
  16870. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16871. */
  16872. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16873. axis.normalize();
  16874. if (!this.rotationQuaternion) {
  16875. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16876. this.rotation.copyFromFloats(0, 0, 0);
  16877. }
  16878. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16879. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16880. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16881. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16882. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16883. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16884. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16885. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16886. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16887. return this;
  16888. };
  16889. /**
  16890. * Translates the mesh along the axis vector for the passed distance in the given space.
  16891. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16892. * Returns the AbstractMesh.
  16893. */
  16894. TransformNode.prototype.translate = function (axis, distance, space) {
  16895. var displacementVector = axis.scale(distance);
  16896. if (!space || space === BABYLON.Space.LOCAL) {
  16897. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16898. this.setPositionWithLocalVector(tempV3);
  16899. }
  16900. else {
  16901. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16902. }
  16903. return this;
  16904. };
  16905. /**
  16906. * Adds a rotation step to the mesh current rotation.
  16907. * x, y, z are Euler angles expressed in radians.
  16908. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16909. * This means this rotation is made in the mesh local space only.
  16910. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16911. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16912. * ```javascript
  16913. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16914. * ```
  16915. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16916. * 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.
  16917. * Returns the AbstractMesh.
  16918. */
  16919. TransformNode.prototype.addRotation = function (x, y, z) {
  16920. var rotationQuaternion;
  16921. if (this.rotationQuaternion) {
  16922. rotationQuaternion = this.rotationQuaternion;
  16923. }
  16924. else {
  16925. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16926. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16927. }
  16928. var accumulation = BABYLON.Tmp.Quaternion[0];
  16929. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16930. rotationQuaternion.multiplyInPlace(accumulation);
  16931. if (!this.rotationQuaternion) {
  16932. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16933. }
  16934. return this;
  16935. };
  16936. /**
  16937. * Computes the mesh World matrix and returns it.
  16938. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16939. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16940. * If the parameter `force`is set to `true`, the actual computation is done.
  16941. * Returns the mesh World Matrix.
  16942. */
  16943. TransformNode.prototype.computeWorldMatrix = function (force) {
  16944. if (this._isWorldMatrixFrozen) {
  16945. return this._worldMatrix;
  16946. }
  16947. if (!force && this.isSynchronized(true)) {
  16948. return this._worldMatrix;
  16949. }
  16950. this._cache.position.copyFrom(this.position);
  16951. this._cache.scaling.copyFrom(this.scaling);
  16952. this._cache.pivotMatrixUpdated = false;
  16953. this._cache.billboardMode = this.billboardMode;
  16954. this._currentRenderId = this.getScene().getRenderId();
  16955. this._isDirty = false;
  16956. // Scaling
  16957. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16958. // Rotation
  16959. //rotate, if quaternion is set and rotation was used
  16960. if (this.rotationQuaternion) {
  16961. var len = this.rotation.length();
  16962. if (len) {
  16963. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16964. this.rotation.copyFromFloats(0, 0, 0);
  16965. }
  16966. }
  16967. if (this.rotationQuaternion) {
  16968. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16969. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16970. }
  16971. else {
  16972. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16973. this._cache.rotation.copyFrom(this.rotation);
  16974. }
  16975. // Translation
  16976. var camera = this.getScene().activeCamera;
  16977. if (this.infiniteDistance && !this.parent && camera) {
  16978. var cameraWorldMatrix = camera.getWorldMatrix();
  16979. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16980. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16981. }
  16982. else {
  16983. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16984. }
  16985. // Composing transformations
  16986. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16987. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16988. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16989. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16990. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16991. // Need to decompose each rotation here
  16992. var currentPosition = BABYLON.Tmp.Vector3[3];
  16993. if (this.parent && this.parent.getWorldMatrix) {
  16994. if (this._transformToBoneReferal) {
  16995. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16996. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16997. }
  16998. else {
  16999. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17000. }
  17001. }
  17002. else {
  17003. currentPosition.copyFrom(this.position);
  17004. }
  17005. currentPosition.subtractInPlace(camera.globalPosition);
  17006. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17007. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17008. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17009. }
  17010. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17011. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17012. }
  17013. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17014. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17015. }
  17016. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17017. }
  17018. else {
  17019. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17020. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17021. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17022. }
  17023. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17024. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17025. }
  17026. // Local world
  17027. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17028. // Parent
  17029. if (this.parent && this.parent.getWorldMatrix) {
  17030. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17031. if (this._transformToBoneReferal) {
  17032. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17033. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17034. }
  17035. else {
  17036. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17037. }
  17038. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17039. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17040. this._worldMatrix.copyFrom(this._localWorld);
  17041. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17042. }
  17043. else {
  17044. if (this._transformToBoneReferal) {
  17045. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17046. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17047. }
  17048. else {
  17049. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17050. }
  17051. }
  17052. this._markSyncedWithParent();
  17053. }
  17054. else {
  17055. this._worldMatrix.copyFrom(this._localWorld);
  17056. }
  17057. // Post multiply inverse of pivotMatrix
  17058. if (this._postMultiplyPivotMatrix) {
  17059. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17060. }
  17061. // Normal matrix
  17062. if (this.scaling.isNonUniform) {
  17063. this._updateNonUniformScalingState(true);
  17064. }
  17065. else if (this.parent && this.parent._nonUniformScaling) {
  17066. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17067. }
  17068. else {
  17069. this._updateNonUniformScalingState(false);
  17070. }
  17071. this._afterComputeWorldMatrix();
  17072. // Absolute position
  17073. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17074. // Callbacks
  17075. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17076. if (!this._poseMatrix) {
  17077. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17078. }
  17079. // Cache the determinant
  17080. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17081. return this._worldMatrix;
  17082. };
  17083. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17084. };
  17085. /**
  17086. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17087. * @param func: callback function to add
  17088. *
  17089. * Returns the TransformNode.
  17090. */
  17091. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17092. this.onAfterWorldMatrixUpdateObservable.add(func);
  17093. return this;
  17094. };
  17095. /**
  17096. * Removes a registered callback function.
  17097. * Returns the TransformNode.
  17098. */
  17099. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17100. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17101. return this;
  17102. };
  17103. /**
  17104. * Clone the current transform node
  17105. * Returns the new transform node
  17106. * @param name Name of the new clone
  17107. * @param newParent New parent for the clone
  17108. * @param doNotCloneChildren Do not clone children hierarchy
  17109. */
  17110. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17111. var _this = this;
  17112. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17113. result.name = name;
  17114. result.id = name;
  17115. if (newParent) {
  17116. result.parent = newParent;
  17117. }
  17118. if (!doNotCloneChildren) {
  17119. // Children
  17120. var directDescendants = this.getDescendants(true);
  17121. for (var index = 0; index < directDescendants.length; index++) {
  17122. var child = directDescendants[index];
  17123. if (child.clone) {
  17124. child.clone(name + "." + child.name, result);
  17125. }
  17126. }
  17127. }
  17128. return result;
  17129. };
  17130. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17131. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17132. serializationObject.type = this.getClassName();
  17133. // Parent
  17134. if (this.parent) {
  17135. serializationObject.parentId = this.parent.id;
  17136. }
  17137. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17138. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17139. }
  17140. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17141. serializationObject.isEnabled = this.isEnabled();
  17142. // Parent
  17143. if (this.parent) {
  17144. serializationObject.parentId = this.parent.id;
  17145. }
  17146. return serializationObject;
  17147. };
  17148. // Statics
  17149. /**
  17150. * Returns a new TransformNode object parsed from the source provided.
  17151. * The parameter `parsedMesh` is the source.
  17152. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17153. */
  17154. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17155. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17156. if (BABYLON.Tags) {
  17157. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17158. }
  17159. if (parsedTransformNode.localMatrix) {
  17160. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17161. }
  17162. else if (parsedTransformNode.pivotMatrix) {
  17163. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17164. }
  17165. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17166. // Parent
  17167. if (parsedTransformNode.parentId) {
  17168. transformNode._waitingParentId = parsedTransformNode.parentId;
  17169. }
  17170. return transformNode;
  17171. };
  17172. /**
  17173. * Releases resources associated with this transform node.
  17174. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17175. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17176. */
  17177. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17178. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17179. // Animations
  17180. this.getScene().stopAnimation(this);
  17181. // Remove from scene
  17182. this.getScene().removeTransformNode(this);
  17183. this.onAfterWorldMatrixUpdateObservable.clear();
  17184. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17185. };
  17186. // Statics
  17187. TransformNode.BILLBOARDMODE_NONE = 0;
  17188. TransformNode.BILLBOARDMODE_X = 1;
  17189. TransformNode.BILLBOARDMODE_Y = 2;
  17190. TransformNode.BILLBOARDMODE_Z = 4;
  17191. TransformNode.BILLBOARDMODE_ALL = 7;
  17192. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17193. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17194. __decorate([
  17195. BABYLON.serializeAsVector3()
  17196. ], TransformNode.prototype, "_rotation", void 0);
  17197. __decorate([
  17198. BABYLON.serializeAsQuaternion()
  17199. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17200. __decorate([
  17201. BABYLON.serializeAsVector3()
  17202. ], TransformNode.prototype, "_scaling", void 0);
  17203. __decorate([
  17204. BABYLON.serialize()
  17205. ], TransformNode.prototype, "billboardMode", void 0);
  17206. __decorate([
  17207. BABYLON.serialize()
  17208. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17209. __decorate([
  17210. BABYLON.serialize()
  17211. ], TransformNode.prototype, "infiniteDistance", void 0);
  17212. __decorate([
  17213. BABYLON.serializeAsVector3()
  17214. ], TransformNode.prototype, "position", void 0);
  17215. return TransformNode;
  17216. }(BABYLON.Node));
  17217. BABYLON.TransformNode = TransformNode;
  17218. })(BABYLON || (BABYLON = {}));
  17219. //# sourceMappingURL=babylon.transformNode.js.map
  17220. var BABYLON;
  17221. (function (BABYLON) {
  17222. var AbstractMesh = /** @class */ (function (_super) {
  17223. __extends(AbstractMesh, _super);
  17224. // Constructor
  17225. function AbstractMesh(name, scene) {
  17226. if (scene === void 0) { scene = null; }
  17227. var _this = _super.call(this, name, scene, false) || this;
  17228. _this._facetNb = 0; // facet number
  17229. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17230. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17231. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17232. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17233. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17234. _this._subDiv = {
  17235. max: 1,
  17236. X: 1,
  17237. Y: 1,
  17238. Z: 1
  17239. };
  17240. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17241. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17242. // Events
  17243. /**
  17244. * An event triggered when this mesh collides with another one
  17245. * @type {BABYLON.Observable}
  17246. */
  17247. _this.onCollideObservable = new BABYLON.Observable();
  17248. /**
  17249. * An event triggered when the collision's position changes
  17250. * @type {BABYLON.Observable}
  17251. */
  17252. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17253. /**
  17254. * An event triggered when material is changed
  17255. * @type {BABYLON.Observable}
  17256. */
  17257. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17258. // Properties
  17259. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17260. /**
  17261. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17262. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17263. * or
  17264. * 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.
  17265. * for more info check WebGl documentations
  17266. */
  17267. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17268. /**
  17269. * 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:
  17270. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17271. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17272. * 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.
  17273. */
  17274. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17275. /**
  17276. * 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.
  17277. * The default value is -1 which means don't break the query and wait till the result.
  17278. */
  17279. _this.occlusionRetryCount = -1;
  17280. _this._occlusionInternalRetryCounter = 0;
  17281. _this._isOccluded = false;
  17282. _this._isOcclusionQueryInProgress = false;
  17283. _this._visibility = 1.0;
  17284. _this.alphaIndex = Number.MAX_VALUE;
  17285. _this.isVisible = true;
  17286. _this.isPickable = true;
  17287. _this.showBoundingBox = false;
  17288. _this.showSubMeshesBoundingBox = false;
  17289. _this.isBlocker = false;
  17290. _this.enablePointerMoveEvents = false;
  17291. _this.renderingGroupId = 0;
  17292. _this._receiveShadows = false;
  17293. _this.renderOutline = false;
  17294. _this.outlineColor = BABYLON.Color3.Red();
  17295. _this.outlineWidth = 0.02;
  17296. _this.renderOverlay = false;
  17297. _this.overlayColor = BABYLON.Color3.Red();
  17298. _this.overlayAlpha = 0.5;
  17299. _this._hasVertexAlpha = false;
  17300. _this._useVertexColors = true;
  17301. _this._computeBonesUsingShaders = true;
  17302. _this._numBoneInfluencers = 4;
  17303. _this._applyFog = true;
  17304. _this.useOctreeForRenderingSelection = true;
  17305. _this.useOctreeForPicking = true;
  17306. _this.useOctreeForCollisions = true;
  17307. _this._layerMask = 0x0FFFFFFF;
  17308. /**
  17309. * True if the mesh must be rendered in any case.
  17310. */
  17311. _this.alwaysSelectAsActiveMesh = false;
  17312. /**
  17313. * This scene's action manager
  17314. * @type {BABYLON.ActionManager}
  17315. */
  17316. _this.actionManager = null;
  17317. // Physics
  17318. _this.physicsImpostor = null;
  17319. // Collisions
  17320. _this._checkCollisions = false;
  17321. _this._collisionMask = -1;
  17322. _this._collisionGroup = -1;
  17323. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17324. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17325. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17326. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17327. // Edges
  17328. _this.edgesWidth = 1;
  17329. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17330. // Cache
  17331. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17332. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17333. _this._renderId = 0;
  17334. _this._intersectionsInProgress = new Array();
  17335. _this._unIndexed = false;
  17336. _this._lightSources = new Array();
  17337. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17338. if (collidedMesh === void 0) { collidedMesh = null; }
  17339. //TODO move this to the collision coordinator!
  17340. if (_this.getScene().workerCollisions)
  17341. newPosition.multiplyInPlace(_this._collider._radius);
  17342. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17343. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17344. _this.position.addInPlace(_this._diffPositionForCollisions);
  17345. }
  17346. if (collidedMesh) {
  17347. _this.onCollideObservable.notifyObservers(collidedMesh);
  17348. }
  17349. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17350. };
  17351. _this.getScene().addMesh(_this);
  17352. _this._resyncLightSources();
  17353. return _this;
  17354. }
  17355. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17356. get: function () {
  17357. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17358. },
  17359. enumerable: true,
  17360. configurable: true
  17361. });
  17362. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17363. get: function () {
  17364. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17365. },
  17366. enumerable: true,
  17367. configurable: true
  17368. });
  17369. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17370. get: function () {
  17371. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17377. get: function () {
  17378. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17379. },
  17380. enumerable: true,
  17381. configurable: true
  17382. });
  17383. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17384. get: function () {
  17385. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17386. },
  17387. enumerable: true,
  17388. configurable: true
  17389. });
  17390. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17391. /**
  17392. * Read-only : the number of facets in the mesh
  17393. */
  17394. get: function () {
  17395. return this._facetNb;
  17396. },
  17397. enumerable: true,
  17398. configurable: true
  17399. });
  17400. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17401. /**
  17402. * The number (integer) of subdivisions per axis in the partioning space
  17403. */
  17404. get: function () {
  17405. return this._partitioningSubdivisions;
  17406. },
  17407. set: function (nb) {
  17408. this._partitioningSubdivisions = nb;
  17409. },
  17410. enumerable: true,
  17411. configurable: true
  17412. });
  17413. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17414. /**
  17415. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17416. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17417. */
  17418. get: function () {
  17419. return this._partitioningBBoxRatio;
  17420. },
  17421. set: function (ratio) {
  17422. this._partitioningBBoxRatio = ratio;
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17428. /**
  17429. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17430. * Works only for updatable meshes.
  17431. * Doesn't work with multi-materials.
  17432. */
  17433. get: function () {
  17434. return this._facetDepthSort;
  17435. },
  17436. set: function (sort) {
  17437. this._facetDepthSort = sort;
  17438. },
  17439. enumerable: true,
  17440. configurable: true
  17441. });
  17442. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17443. /**
  17444. * The location (Vector3) where the facet depth sort must be computed from.
  17445. * By default, the active camera position.
  17446. * Used only when facet depth sort is enabled.
  17447. */
  17448. get: function () {
  17449. return this._facetDepthSortFrom;
  17450. },
  17451. set: function (location) {
  17452. this._facetDepthSortFrom = location;
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17458. /**
  17459. * Read-only boolean : is the feature facetData enabled ?
  17460. */
  17461. get: function () {
  17462. return this._facetDataEnabled;
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17468. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17469. return false;
  17470. }
  17471. this._markSubMeshesAsMiscDirty();
  17472. return true;
  17473. };
  17474. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17475. set: function (callback) {
  17476. if (this._onCollideObserver) {
  17477. this.onCollideObservable.remove(this._onCollideObserver);
  17478. }
  17479. this._onCollideObserver = this.onCollideObservable.add(callback);
  17480. },
  17481. enumerable: true,
  17482. configurable: true
  17483. });
  17484. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17485. set: function (callback) {
  17486. if (this._onCollisionPositionChangeObserver) {
  17487. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17488. }
  17489. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17490. },
  17491. enumerable: true,
  17492. configurable: true
  17493. });
  17494. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17495. /**
  17496. * 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.
  17497. */
  17498. get: function () {
  17499. return this._isOccluded;
  17500. },
  17501. set: function (value) {
  17502. this._isOccluded = value;
  17503. },
  17504. enumerable: true,
  17505. configurable: true
  17506. });
  17507. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17508. /**
  17509. * Flag to check the progress status of the query
  17510. */
  17511. get: function () {
  17512. return this._isOcclusionQueryInProgress;
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17518. /**
  17519. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17520. */
  17521. get: function () {
  17522. return this._visibility;
  17523. },
  17524. /**
  17525. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17526. */
  17527. set: function (value) {
  17528. if (this._visibility === value) {
  17529. return;
  17530. }
  17531. this._visibility = value;
  17532. this._markSubMeshesAsMiscDirty();
  17533. },
  17534. enumerable: true,
  17535. configurable: true
  17536. });
  17537. Object.defineProperty(AbstractMesh.prototype, "material", {
  17538. get: function () {
  17539. return this._material;
  17540. },
  17541. set: function (value) {
  17542. if (this._material === value) {
  17543. return;
  17544. }
  17545. this._material = value;
  17546. if (this.onMaterialChangedObservable.hasObservers) {
  17547. this.onMaterialChangedObservable.notifyObservers(this);
  17548. }
  17549. if (!this.subMeshes) {
  17550. return;
  17551. }
  17552. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17553. var subMesh = _a[_i];
  17554. subMesh.setEffect(null);
  17555. }
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17561. get: function () {
  17562. return this._receiveShadows;
  17563. },
  17564. set: function (value) {
  17565. if (this._receiveShadows === value) {
  17566. return;
  17567. }
  17568. this._receiveShadows = value;
  17569. this._markSubMeshesAsLightDirty();
  17570. },
  17571. enumerable: true,
  17572. configurable: true
  17573. });
  17574. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17575. get: function () {
  17576. return this._hasVertexAlpha;
  17577. },
  17578. set: function (value) {
  17579. if (this._hasVertexAlpha === value) {
  17580. return;
  17581. }
  17582. this._hasVertexAlpha = value;
  17583. this._markSubMeshesAsAttributesDirty();
  17584. this._markSubMeshesAsMiscDirty();
  17585. },
  17586. enumerable: true,
  17587. configurable: true
  17588. });
  17589. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17590. get: function () {
  17591. return this._useVertexColors;
  17592. },
  17593. set: function (value) {
  17594. if (this._useVertexColors === value) {
  17595. return;
  17596. }
  17597. this._useVertexColors = value;
  17598. this._markSubMeshesAsAttributesDirty();
  17599. },
  17600. enumerable: true,
  17601. configurable: true
  17602. });
  17603. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17604. get: function () {
  17605. return this._computeBonesUsingShaders;
  17606. },
  17607. set: function (value) {
  17608. if (this._computeBonesUsingShaders === value) {
  17609. return;
  17610. }
  17611. this._computeBonesUsingShaders = value;
  17612. this._markSubMeshesAsAttributesDirty();
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17618. get: function () {
  17619. return this._numBoneInfluencers;
  17620. },
  17621. set: function (value) {
  17622. if (this._numBoneInfluencers === value) {
  17623. return;
  17624. }
  17625. this._numBoneInfluencers = value;
  17626. this._markSubMeshesAsAttributesDirty();
  17627. },
  17628. enumerable: true,
  17629. configurable: true
  17630. });
  17631. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17632. get: function () {
  17633. return this._applyFog;
  17634. },
  17635. set: function (value) {
  17636. if (this._applyFog === value) {
  17637. return;
  17638. }
  17639. this._applyFog = value;
  17640. this._markSubMeshesAsMiscDirty();
  17641. },
  17642. enumerable: true,
  17643. configurable: true
  17644. });
  17645. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17646. get: function () {
  17647. return this._layerMask;
  17648. },
  17649. set: function (value) {
  17650. if (value === this._layerMask) {
  17651. return;
  17652. }
  17653. this._layerMask = value;
  17654. this._resyncLightSources();
  17655. },
  17656. enumerable: true,
  17657. configurable: true
  17658. });
  17659. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17660. get: function () {
  17661. return this._collisionMask;
  17662. },
  17663. set: function (mask) {
  17664. this._collisionMask = !isNaN(mask) ? mask : -1;
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17670. get: function () {
  17671. return this._collisionGroup;
  17672. },
  17673. set: function (mask) {
  17674. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17680. get: function () {
  17681. return null;
  17682. },
  17683. enumerable: true,
  17684. configurable: true
  17685. });
  17686. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17687. get: function () {
  17688. return this._skeleton;
  17689. },
  17690. set: function (value) {
  17691. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17692. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17693. }
  17694. if (value && value.needInitialSkinMatrix) {
  17695. value._registerMeshWithPoseMatrix(this);
  17696. }
  17697. this._skeleton = value;
  17698. if (!this._skeleton) {
  17699. this._bonesTransformMatrices = null;
  17700. }
  17701. this._markSubMeshesAsAttributesDirty();
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. /**
  17707. * Returns the string "AbstractMesh"
  17708. */
  17709. AbstractMesh.prototype.getClassName = function () {
  17710. return "AbstractMesh";
  17711. };
  17712. /**
  17713. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17714. */
  17715. AbstractMesh.prototype.toString = function (fullDetails) {
  17716. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17717. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17718. if (this._skeleton) {
  17719. ret += ", skeleton: " + this._skeleton.name;
  17720. }
  17721. if (fullDetails) {
  17722. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17723. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17724. }
  17725. return ret;
  17726. };
  17727. AbstractMesh.prototype._rebuild = function () {
  17728. if (this._occlusionQuery) {
  17729. this._occlusionQuery = null;
  17730. }
  17731. if (this._edgesRenderer) {
  17732. this._edgesRenderer._rebuild();
  17733. }
  17734. if (!this.subMeshes) {
  17735. return;
  17736. }
  17737. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17738. var subMesh = _a[_i];
  17739. subMesh._rebuild();
  17740. }
  17741. };
  17742. AbstractMesh.prototype._resyncLightSources = function () {
  17743. this._lightSources.length = 0;
  17744. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17745. var light = _a[_i];
  17746. if (!light.isEnabled()) {
  17747. continue;
  17748. }
  17749. if (light.canAffectMesh(this)) {
  17750. this._lightSources.push(light);
  17751. }
  17752. }
  17753. this._markSubMeshesAsLightDirty();
  17754. };
  17755. AbstractMesh.prototype._resyncLighSource = function (light) {
  17756. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17757. var index = this._lightSources.indexOf(light);
  17758. if (index === -1) {
  17759. if (!isIn) {
  17760. return;
  17761. }
  17762. this._lightSources.push(light);
  17763. }
  17764. else {
  17765. if (isIn) {
  17766. return;
  17767. }
  17768. this._lightSources.splice(index, 1);
  17769. }
  17770. this._markSubMeshesAsLightDirty();
  17771. };
  17772. AbstractMesh.prototype._removeLightSource = function (light) {
  17773. var index = this._lightSources.indexOf(light);
  17774. if (index === -1) {
  17775. return;
  17776. }
  17777. this._lightSources.splice(index, 1);
  17778. this._markSubMeshesAsLightDirty();
  17779. };
  17780. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17781. if (!this.subMeshes) {
  17782. return;
  17783. }
  17784. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17785. var subMesh = _a[_i];
  17786. if (subMesh._materialDefines) {
  17787. func(subMesh._materialDefines);
  17788. }
  17789. }
  17790. };
  17791. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17792. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17793. };
  17794. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17795. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17796. };
  17797. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17798. if (!this.subMeshes) {
  17799. return;
  17800. }
  17801. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17802. var subMesh = _a[_i];
  17803. var material = subMesh.getMaterial();
  17804. if (material) {
  17805. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17806. }
  17807. }
  17808. };
  17809. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17810. /**
  17811. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17812. * Default : (1.0, 1.0, 1.0)
  17813. */
  17814. get: function () {
  17815. return this._scaling;
  17816. },
  17817. /**
  17818. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17819. * Default : (1.0, 1.0, 1.0)
  17820. */
  17821. set: function (newScaling) {
  17822. this._scaling = newScaling;
  17823. if (this.physicsImpostor) {
  17824. this.physicsImpostor.forceUpdate();
  17825. }
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. // Methods
  17831. /**
  17832. * Disables the mesh edger rendering mode.
  17833. * Returns the AbstractMesh.
  17834. */
  17835. AbstractMesh.prototype.disableEdgesRendering = function () {
  17836. if (this._edgesRenderer) {
  17837. this._edgesRenderer.dispose();
  17838. this._edgesRenderer = null;
  17839. }
  17840. return this;
  17841. };
  17842. /**
  17843. * Enables the edge rendering mode on the mesh.
  17844. * This mode makes the mesh edges visible.
  17845. * Returns the AbstractMesh.
  17846. */
  17847. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17848. if (epsilon === void 0) { epsilon = 0.95; }
  17849. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17850. this.disableEdgesRendering();
  17851. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17852. return this;
  17853. };
  17854. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17855. /**
  17856. * Returns true if the mesh is blocked. Used by the class Mesh.
  17857. * Returns the boolean `false` by default.
  17858. */
  17859. get: function () {
  17860. return false;
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. /**
  17866. * Returns the mesh itself by default, used by the class Mesh.
  17867. * Returned type : AbstractMesh
  17868. */
  17869. AbstractMesh.prototype.getLOD = function (camera) {
  17870. return this;
  17871. };
  17872. /**
  17873. * Returns 0 by default, used by the class Mesh.
  17874. * Returns an integer.
  17875. */
  17876. AbstractMesh.prototype.getTotalVertices = function () {
  17877. return 0;
  17878. };
  17879. /**
  17880. * Returns null by default, used by the class Mesh.
  17881. * Returned type : integer array
  17882. */
  17883. AbstractMesh.prototype.getIndices = function () {
  17884. return null;
  17885. };
  17886. /**
  17887. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17888. * Returned type : float array or Float32Array
  17889. */
  17890. AbstractMesh.prototype.getVerticesData = function (kind) {
  17891. return null;
  17892. };
  17893. /**
  17894. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17895. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17896. * The `data` are either a numeric array either a Float32Array.
  17897. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17898. * 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).
  17899. * Note that a new underlying VertexBuffer object is created each call.
  17900. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17901. *
  17902. * Possible `kind` values :
  17903. * - BABYLON.VertexBuffer.PositionKind
  17904. * - BABYLON.VertexBuffer.UVKind
  17905. * - BABYLON.VertexBuffer.UV2Kind
  17906. * - BABYLON.VertexBuffer.UV3Kind
  17907. * - BABYLON.VertexBuffer.UV4Kind
  17908. * - BABYLON.VertexBuffer.UV5Kind
  17909. * - BABYLON.VertexBuffer.UV6Kind
  17910. * - BABYLON.VertexBuffer.ColorKind
  17911. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17912. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17913. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17914. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17915. *
  17916. * Returns the Mesh.
  17917. */
  17918. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17919. return this;
  17920. };
  17921. /**
  17922. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17923. * If the mesh has no geometry, it is simply returned as it is.
  17924. * The `data` are either a numeric array either a Float32Array.
  17925. * No new underlying VertexBuffer object is created.
  17926. * 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.
  17927. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17928. *
  17929. * Possible `kind` values :
  17930. * - BABYLON.VertexBuffer.PositionKind
  17931. * - BABYLON.VertexBuffer.UVKind
  17932. * - BABYLON.VertexBuffer.UV2Kind
  17933. * - BABYLON.VertexBuffer.UV3Kind
  17934. * - BABYLON.VertexBuffer.UV4Kind
  17935. * - BABYLON.VertexBuffer.UV5Kind
  17936. * - BABYLON.VertexBuffer.UV6Kind
  17937. * - BABYLON.VertexBuffer.ColorKind
  17938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17942. *
  17943. * Returns the Mesh.
  17944. */
  17945. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17946. return this;
  17947. };
  17948. /**
  17949. * Sets the mesh indices.
  17950. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17951. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17952. * This method creates a new index buffer each call.
  17953. * Returns the Mesh.
  17954. */
  17955. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17956. return this;
  17957. };
  17958. /** Returns false by default, used by the class Mesh.
  17959. * Returns a boolean
  17960. */
  17961. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17962. return false;
  17963. };
  17964. /**
  17965. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17966. * Returns a BoundingInfo
  17967. */
  17968. AbstractMesh.prototype.getBoundingInfo = function () {
  17969. if (this._masterMesh) {
  17970. return this._masterMesh.getBoundingInfo();
  17971. }
  17972. if (!this._boundingInfo) {
  17973. // this._boundingInfo is being created here
  17974. this._updateBoundingInfo();
  17975. }
  17976. // cannot be null.
  17977. return this._boundingInfo;
  17978. };
  17979. /**
  17980. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17981. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17982. */
  17983. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17984. if (includeDescendants === void 0) { includeDescendants = true; }
  17985. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17986. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17987. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17988. if (maxDimension === 0) {
  17989. return this;
  17990. }
  17991. var scale = 1 / maxDimension;
  17992. this.scaling.scaleInPlace(scale);
  17993. return this;
  17994. };
  17995. /**
  17996. * Sets a mesh new object BoundingInfo.
  17997. * Returns the AbstractMesh.
  17998. */
  17999. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18000. this._boundingInfo = boundingInfo;
  18001. return this;
  18002. };
  18003. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18004. get: function () {
  18005. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. AbstractMesh.prototype._preActivate = function () {
  18011. };
  18012. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18013. };
  18014. AbstractMesh.prototype._activate = function (renderId) {
  18015. this._renderId = renderId;
  18016. };
  18017. /**
  18018. * Returns the latest update of the World matrix
  18019. * Returns a Matrix.
  18020. */
  18021. AbstractMesh.prototype.getWorldMatrix = function () {
  18022. if (this._masterMesh) {
  18023. return this._masterMesh.getWorldMatrix();
  18024. }
  18025. return _super.prototype.getWorldMatrix.call(this);
  18026. };
  18027. /**
  18028. * Returns the latest update of the World matrix determinant.
  18029. */
  18030. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18031. if (this._masterMesh) {
  18032. return this._masterMesh._getWorldMatrixDeterminant();
  18033. }
  18034. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18035. };
  18036. // ================================== Point of View Movement =================================
  18037. /**
  18038. * Perform relative position change from the point of view of behind the front of the mesh.
  18039. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18040. * Supports definition of mesh facing forward or backward.
  18041. * @param {number} amountRight
  18042. * @param {number} amountUp
  18043. * @param {number} amountForward
  18044. *
  18045. * Returns the AbstractMesh.
  18046. */
  18047. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18048. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18049. return this;
  18050. };
  18051. /**
  18052. * Calculate relative position change from the point of view of behind the front of the mesh.
  18053. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18054. * Supports definition of mesh facing forward or backward.
  18055. * @param {number} amountRight
  18056. * @param {number} amountUp
  18057. * @param {number} amountForward
  18058. *
  18059. * Returns a new Vector3.
  18060. */
  18061. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18062. var rotMatrix = new BABYLON.Matrix();
  18063. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18064. rotQuaternion.toRotationMatrix(rotMatrix);
  18065. var translationDelta = BABYLON.Vector3.Zero();
  18066. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18067. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18068. return translationDelta;
  18069. };
  18070. // ================================== Point of View Rotation =================================
  18071. /**
  18072. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18073. * Supports definition of mesh facing forward or backward.
  18074. * @param {number} flipBack
  18075. * @param {number} twirlClockwise
  18076. * @param {number} tiltRight
  18077. *
  18078. * Returns the AbstractMesh.
  18079. */
  18080. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18081. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18082. return this;
  18083. };
  18084. /**
  18085. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18086. * Supports definition of mesh facing forward or backward.
  18087. * @param {number} flipBack
  18088. * @param {number} twirlClockwise
  18089. * @param {number} tiltRight
  18090. *
  18091. * Returns a new Vector3.
  18092. */
  18093. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18094. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18095. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18096. };
  18097. /**
  18098. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18099. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18100. */
  18101. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18102. if (includeDescendants === void 0) { includeDescendants = true; }
  18103. this.computeWorldMatrix(true);
  18104. var min;
  18105. var max;
  18106. var boundingInfo = this.getBoundingInfo();
  18107. if (!this.subMeshes) {
  18108. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18109. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18110. }
  18111. else {
  18112. min = boundingInfo.boundingBox.minimumWorld;
  18113. max = boundingInfo.boundingBox.maximumWorld;
  18114. }
  18115. if (includeDescendants) {
  18116. var descendants = this.getDescendants(false);
  18117. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18118. var descendant = descendants_1[_i];
  18119. var childMesh = descendant;
  18120. childMesh.computeWorldMatrix(true);
  18121. //make sure we have the needed params to get mix and max
  18122. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18123. continue;
  18124. }
  18125. var childBoundingInfo = childMesh.getBoundingInfo();
  18126. var boundingBox = childBoundingInfo.boundingBox;
  18127. var minBox = boundingBox.minimumWorld;
  18128. var maxBox = boundingBox.maximumWorld;
  18129. BABYLON.Tools.CheckExtends(minBox, min, max);
  18130. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18131. }
  18132. }
  18133. return {
  18134. min: min,
  18135. max: max
  18136. };
  18137. };
  18138. /**
  18139. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18140. * Returns the AbstractMesh.
  18141. */
  18142. AbstractMesh.prototype._updateBoundingInfo = function () {
  18143. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18144. this._boundingInfo.update(this.worldMatrixFromCache);
  18145. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18146. return this;
  18147. };
  18148. /**
  18149. * Update a mesh's children BoundingInfo objects only.
  18150. * Returns the AbstractMesh.
  18151. */
  18152. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18153. if (!this.subMeshes) {
  18154. return this;
  18155. }
  18156. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18157. var subMesh = this.subMeshes[subIndex];
  18158. if (!subMesh.IsGlobal) {
  18159. subMesh.updateBoundingInfo(matrix);
  18160. }
  18161. }
  18162. return this;
  18163. };
  18164. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18165. // Bounding info
  18166. this._updateBoundingInfo();
  18167. };
  18168. /**
  18169. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18170. * A mesh is in the frustum if its bounding box intersects the frustum.
  18171. * Boolean returned.
  18172. */
  18173. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18174. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18175. };
  18176. /**
  18177. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18178. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18179. * Boolean returned.
  18180. */
  18181. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18182. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18183. ;
  18184. };
  18185. /**
  18186. * True if the mesh intersects another mesh or a SolidParticle object.
  18187. * 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)
  18188. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18189. * Returns a boolean.
  18190. */
  18191. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18192. if (precise === void 0) { precise = false; }
  18193. if (!this._boundingInfo || !mesh._boundingInfo) {
  18194. return false;
  18195. }
  18196. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18197. return true;
  18198. }
  18199. if (includeDescendants) {
  18200. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18201. var child = _a[_i];
  18202. if (child.intersectsMesh(mesh, precise, true)) {
  18203. return true;
  18204. }
  18205. }
  18206. }
  18207. return false;
  18208. };
  18209. /**
  18210. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18211. * Returns a boolean.
  18212. */
  18213. AbstractMesh.prototype.intersectsPoint = function (point) {
  18214. if (!this._boundingInfo) {
  18215. return false;
  18216. }
  18217. return this._boundingInfo.intersectsPoint(point);
  18218. };
  18219. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18220. return this.physicsImpostor;
  18221. };
  18222. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18223. if (camera === void 0) { camera = null; }
  18224. if (!camera) {
  18225. camera = this.getScene().activeCamera;
  18226. }
  18227. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18228. };
  18229. /**
  18230. * Returns the distance from the mesh to the active camera.
  18231. * Returns a float.
  18232. */
  18233. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18234. if (camera === void 0) { camera = null; }
  18235. if (!camera) {
  18236. camera = this.getScene().activeCamera;
  18237. }
  18238. return this.absolutePosition.subtract(camera.position).length();
  18239. };
  18240. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18241. if (!this.physicsImpostor) {
  18242. return this;
  18243. }
  18244. this.physicsImpostor.applyImpulse(force, contactPoint);
  18245. return this;
  18246. };
  18247. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18248. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18249. return this;
  18250. }
  18251. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18252. mainPivot: pivot1,
  18253. connectedPivot: pivot2,
  18254. nativeParams: options
  18255. });
  18256. return this;
  18257. };
  18258. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18259. // Collisions
  18260. /**
  18261. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18262. * Default `false`.
  18263. */
  18264. get: function () {
  18265. return this._checkCollisions;
  18266. },
  18267. set: function (collisionEnabled) {
  18268. this._checkCollisions = collisionEnabled;
  18269. if (this.getScene().workerCollisions) {
  18270. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18271. }
  18272. },
  18273. enumerable: true,
  18274. configurable: true
  18275. });
  18276. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18277. /**
  18278. * Gets Collider object used to compute collisions (not physics)
  18279. */
  18280. get: function () {
  18281. return this._collider;
  18282. },
  18283. enumerable: true,
  18284. configurable: true
  18285. });
  18286. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18287. var globalPosition = this.getAbsolutePosition();
  18288. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18289. if (!this._collider) {
  18290. this._collider = new BABYLON.Collider();
  18291. }
  18292. this._collider._radius = this.ellipsoid;
  18293. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18294. return this;
  18295. };
  18296. // Submeshes octree
  18297. /**
  18298. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18299. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18300. * Returns an Octree of submeshes.
  18301. */
  18302. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18303. if (maxCapacity === void 0) { maxCapacity = 64; }
  18304. if (maxDepth === void 0) { maxDepth = 2; }
  18305. if (!this._submeshesOctree) {
  18306. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18307. }
  18308. this.computeWorldMatrix(true);
  18309. var boundingInfo = this.getBoundingInfo();
  18310. // Update octree
  18311. var bbox = boundingInfo.boundingBox;
  18312. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18313. return this._submeshesOctree;
  18314. };
  18315. // Collisions
  18316. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18317. this._generatePointsArray();
  18318. if (!this._positions) {
  18319. return this;
  18320. }
  18321. // Transformation
  18322. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18323. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18324. subMesh._lastColliderWorldVertices = [];
  18325. subMesh._trianglePlanes = [];
  18326. var start = subMesh.verticesStart;
  18327. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18328. for (var i = start; i < end; i++) {
  18329. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18330. }
  18331. }
  18332. // Collide
  18333. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18334. if (collider.collisionFound) {
  18335. collider.collidedMesh = this;
  18336. }
  18337. return this;
  18338. };
  18339. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18340. var subMeshes;
  18341. var len;
  18342. // Octrees
  18343. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18344. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18345. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18346. len = intersections.length;
  18347. subMeshes = intersections.data;
  18348. }
  18349. else {
  18350. subMeshes = this.subMeshes;
  18351. len = subMeshes.length;
  18352. }
  18353. for (var index = 0; index < len; index++) {
  18354. var subMesh = subMeshes[index];
  18355. // Bounding test
  18356. if (len > 1 && !subMesh._checkCollision(collider))
  18357. continue;
  18358. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18359. }
  18360. return this;
  18361. };
  18362. AbstractMesh.prototype._checkCollision = function (collider) {
  18363. // Bounding box test
  18364. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18365. return this;
  18366. // Transformation matrix
  18367. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18368. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18369. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18370. return this;
  18371. };
  18372. // Picking
  18373. AbstractMesh.prototype._generatePointsArray = function () {
  18374. return false;
  18375. };
  18376. /**
  18377. * Checks if the passed Ray intersects with the mesh.
  18378. * Returns an object PickingInfo.
  18379. */
  18380. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18381. var pickingInfo = new BABYLON.PickingInfo();
  18382. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18383. return pickingInfo;
  18384. }
  18385. if (!this._generatePointsArray()) {
  18386. return pickingInfo;
  18387. }
  18388. var intersectInfo = null;
  18389. // Octrees
  18390. var subMeshes;
  18391. var len;
  18392. if (this._submeshesOctree && this.useOctreeForPicking) {
  18393. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18394. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18395. len = intersections.length;
  18396. subMeshes = intersections.data;
  18397. }
  18398. else {
  18399. subMeshes = this.subMeshes;
  18400. len = subMeshes.length;
  18401. }
  18402. for (var index = 0; index < len; index++) {
  18403. var subMesh = subMeshes[index];
  18404. // Bounding test
  18405. if (len > 1 && !subMesh.canIntersects(ray))
  18406. continue;
  18407. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18408. if (currentIntersectInfo) {
  18409. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18410. intersectInfo = currentIntersectInfo;
  18411. intersectInfo.subMeshId = index;
  18412. if (fastCheck) {
  18413. break;
  18414. }
  18415. }
  18416. }
  18417. }
  18418. if (intersectInfo) {
  18419. // Get picked point
  18420. var world = this.getWorldMatrix();
  18421. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18422. var direction = ray.direction.clone();
  18423. direction = direction.scale(intersectInfo.distance);
  18424. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18425. var pickedPoint = worldOrigin.add(worldDirection);
  18426. // Return result
  18427. pickingInfo.hit = true;
  18428. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18429. pickingInfo.pickedPoint = pickedPoint;
  18430. pickingInfo.pickedMesh = this;
  18431. pickingInfo.bu = intersectInfo.bu || 0;
  18432. pickingInfo.bv = intersectInfo.bv || 0;
  18433. pickingInfo.faceId = intersectInfo.faceId;
  18434. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18435. return pickingInfo;
  18436. }
  18437. return pickingInfo;
  18438. };
  18439. /**
  18440. * Clones the mesh, used by the class Mesh.
  18441. * Just returns `null` for an AbstractMesh.
  18442. */
  18443. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18444. return null;
  18445. };
  18446. /**
  18447. * Disposes all the mesh submeshes.
  18448. * Returns the AbstractMesh.
  18449. */
  18450. AbstractMesh.prototype.releaseSubMeshes = function () {
  18451. if (this.subMeshes) {
  18452. while (this.subMeshes.length) {
  18453. this.subMeshes[0].dispose();
  18454. }
  18455. }
  18456. else {
  18457. this.subMeshes = new Array();
  18458. }
  18459. return this;
  18460. };
  18461. /**
  18462. * Releases resources associated with this abstract mesh.
  18463. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18464. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18465. */
  18466. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18467. var _this = this;
  18468. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18469. var index;
  18470. // Smart Array Retainers.
  18471. this.getScene().freeActiveMeshes();
  18472. this.getScene().freeRenderingGroups();
  18473. // Action manager
  18474. if (this.actionManager !== undefined && this.actionManager !== null) {
  18475. this.actionManager.dispose();
  18476. this.actionManager = null;
  18477. }
  18478. // Skeleton
  18479. this.skeleton = null;
  18480. // Physics
  18481. if (this.physicsImpostor) {
  18482. this.physicsImpostor.dispose();
  18483. }
  18484. // Intersections in progress
  18485. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18486. var other = this._intersectionsInProgress[index];
  18487. var pos = other._intersectionsInProgress.indexOf(this);
  18488. other._intersectionsInProgress.splice(pos, 1);
  18489. }
  18490. this._intersectionsInProgress = [];
  18491. // Lights
  18492. var lights = this.getScene().lights;
  18493. lights.forEach(function (light) {
  18494. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18495. if (meshIndex !== -1) {
  18496. light.includedOnlyMeshes.splice(meshIndex, 1);
  18497. }
  18498. meshIndex = light.excludedMeshes.indexOf(_this);
  18499. if (meshIndex !== -1) {
  18500. light.excludedMeshes.splice(meshIndex, 1);
  18501. }
  18502. // Shadow generators
  18503. var generator = light.getShadowGenerator();
  18504. if (generator) {
  18505. var shadowMap = generator.getShadowMap();
  18506. if (shadowMap && shadowMap.renderList) {
  18507. meshIndex = shadowMap.renderList.indexOf(_this);
  18508. if (meshIndex !== -1) {
  18509. shadowMap.renderList.splice(meshIndex, 1);
  18510. }
  18511. }
  18512. }
  18513. });
  18514. // Edges
  18515. if (this._edgesRenderer) {
  18516. this._edgesRenderer.dispose();
  18517. this._edgesRenderer = null;
  18518. }
  18519. // SubMeshes
  18520. if (this.getClassName() !== "InstancedMesh") {
  18521. this.releaseSubMeshes();
  18522. }
  18523. // Octree
  18524. var sceneOctree = this.getScene().selectionOctree;
  18525. if (sceneOctree !== undefined && sceneOctree !== null) {
  18526. var index = sceneOctree.dynamicContent.indexOf(this);
  18527. if (index !== -1) {
  18528. sceneOctree.dynamicContent.splice(index, 1);
  18529. }
  18530. }
  18531. // Query
  18532. var engine = this.getScene().getEngine();
  18533. if (this._occlusionQuery) {
  18534. this._isOcclusionQueryInProgress = false;
  18535. engine.deleteQuery(this._occlusionQuery);
  18536. this._occlusionQuery = null;
  18537. }
  18538. // Engine
  18539. engine.wipeCaches();
  18540. // Remove from scene
  18541. this.getScene().removeMesh(this);
  18542. if (disposeMaterialAndTextures) {
  18543. if (this.material) {
  18544. this.material.dispose(false, true);
  18545. }
  18546. }
  18547. if (!doNotRecurse) {
  18548. // Particles
  18549. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18550. if (this.getScene().particleSystems[index].emitter === this) {
  18551. this.getScene().particleSystems[index].dispose();
  18552. index--;
  18553. }
  18554. }
  18555. }
  18556. // facet data
  18557. if (this._facetDataEnabled) {
  18558. this.disableFacetData();
  18559. }
  18560. this.onAfterWorldMatrixUpdateObservable.clear();
  18561. this.onCollideObservable.clear();
  18562. this.onCollisionPositionChangeObservable.clear();
  18563. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18564. };
  18565. /**
  18566. * Adds the passed mesh as a child to the current mesh.
  18567. * Returns the AbstractMesh.
  18568. */
  18569. AbstractMesh.prototype.addChild = function (mesh) {
  18570. mesh.setParent(this);
  18571. return this;
  18572. };
  18573. /**
  18574. * Removes the passed mesh from the current mesh children list.
  18575. * Returns the AbstractMesh.
  18576. */
  18577. AbstractMesh.prototype.removeChild = function (mesh) {
  18578. mesh.setParent(null);
  18579. return this;
  18580. };
  18581. // Facet data
  18582. /**
  18583. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18584. * Returns the AbstractMesh.
  18585. */
  18586. AbstractMesh.prototype._initFacetData = function () {
  18587. if (!this._facetNormals) {
  18588. this._facetNormals = new Array();
  18589. }
  18590. if (!this._facetPositions) {
  18591. this._facetPositions = new Array();
  18592. }
  18593. if (!this._facetPartitioning) {
  18594. this._facetPartitioning = new Array();
  18595. }
  18596. this._facetNb = (this.getIndices().length / 3) | 0;
  18597. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18598. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18599. for (var f = 0; f < this._facetNb; f++) {
  18600. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18601. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18602. }
  18603. this._facetDataEnabled = true;
  18604. return this;
  18605. };
  18606. /**
  18607. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18608. * This method can be called within the render loop.
  18609. * 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.
  18610. * Returns the AbstractMesh.
  18611. */
  18612. AbstractMesh.prototype.updateFacetData = function () {
  18613. if (!this._facetDataEnabled) {
  18614. this._initFacetData();
  18615. }
  18616. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18617. var indices = this.getIndices();
  18618. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18619. var bInfo = this.getBoundingInfo();
  18620. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18621. // init arrays, matrix and sort function on first call
  18622. this._facetDepthSortEnabled = true;
  18623. if (indices instanceof Uint16Array) {
  18624. this._depthSortedIndices = new Uint16Array(indices);
  18625. }
  18626. else if (indices instanceof Uint32Array) {
  18627. this._depthSortedIndices = new Uint32Array(indices);
  18628. }
  18629. else {
  18630. var needs32bits = false;
  18631. for (var i = 0; i < indices.length; i++) {
  18632. if (indices[i] > 65535) {
  18633. needs32bits = true;
  18634. break;
  18635. }
  18636. }
  18637. if (needs32bits) {
  18638. this._depthSortedIndices = new Uint32Array(indices);
  18639. }
  18640. else {
  18641. this._depthSortedIndices = new Uint16Array(indices);
  18642. }
  18643. }
  18644. this._facetDepthSortFunction = function (f1, f2) {
  18645. return (f2.sqDistance - f1.sqDistance);
  18646. };
  18647. if (!this._facetDepthSortFrom) {
  18648. var camera = this.getScene().activeCamera;
  18649. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18650. }
  18651. this._depthSortedFacets = [];
  18652. for (var f = 0; f < this._facetNb; f++) {
  18653. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18654. this._depthSortedFacets.push(depthSortedFacet);
  18655. }
  18656. this._invertedMatrix = BABYLON.Matrix.Identity();
  18657. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18658. }
  18659. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18660. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18661. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18662. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18663. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18664. this._subDiv.max = this._partitioningSubdivisions;
  18665. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18666. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18667. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18668. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18669. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18670. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18671. // set the parameters for ComputeNormals()
  18672. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18673. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18674. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18675. this._facetParameters.bInfo = bInfo;
  18676. this._facetParameters.bbSize = this._bbSize;
  18677. this._facetParameters.subDiv = this._subDiv;
  18678. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18679. this._facetParameters.depthSort = this._facetDepthSort;
  18680. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18681. this.computeWorldMatrix(true);
  18682. this._worldMatrix.invertToRef(this._invertedMatrix);
  18683. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18684. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18685. }
  18686. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18687. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18688. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18689. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18690. var l = (this._depthSortedIndices.length / 3) | 0;
  18691. for (var f = 0; f < l; f++) {
  18692. var sind = this._depthSortedFacets[f].ind;
  18693. this._depthSortedIndices[f * 3] = indices[sind];
  18694. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18695. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18696. }
  18697. this.updateIndices(this._depthSortedIndices);
  18698. }
  18699. return this;
  18700. };
  18701. /**
  18702. * Returns the facetLocalNormals array.
  18703. * The normals are expressed in the mesh local space.
  18704. */
  18705. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18706. if (!this._facetNormals) {
  18707. this.updateFacetData();
  18708. }
  18709. return this._facetNormals;
  18710. };
  18711. /**
  18712. * Returns the facetLocalPositions array.
  18713. * The facet positions are expressed in the mesh local space.
  18714. */
  18715. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18716. if (!this._facetPositions) {
  18717. this.updateFacetData();
  18718. }
  18719. return this._facetPositions;
  18720. };
  18721. /**
  18722. * Returns the facetLocalPartioning array.
  18723. */
  18724. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18725. if (!this._facetPartitioning) {
  18726. this.updateFacetData();
  18727. }
  18728. return this._facetPartitioning;
  18729. };
  18730. /**
  18731. * Returns the i-th facet position in the world system.
  18732. * This method allocates a new Vector3 per call.
  18733. */
  18734. AbstractMesh.prototype.getFacetPosition = function (i) {
  18735. var pos = BABYLON.Vector3.Zero();
  18736. this.getFacetPositionToRef(i, pos);
  18737. return pos;
  18738. };
  18739. /**
  18740. * Sets the reference Vector3 with the i-th facet position in the world system.
  18741. * Returns the AbstractMesh.
  18742. */
  18743. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18744. var localPos = (this.getFacetLocalPositions())[i];
  18745. var world = this.getWorldMatrix();
  18746. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18747. return this;
  18748. };
  18749. /**
  18750. * Returns the i-th facet normal in the world system.
  18751. * This method allocates a new Vector3 per call.
  18752. */
  18753. AbstractMesh.prototype.getFacetNormal = function (i) {
  18754. var norm = BABYLON.Vector3.Zero();
  18755. this.getFacetNormalToRef(i, norm);
  18756. return norm;
  18757. };
  18758. /**
  18759. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18760. * Returns the AbstractMesh.
  18761. */
  18762. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18763. var localNorm = (this.getFacetLocalNormals())[i];
  18764. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18765. return this;
  18766. };
  18767. /**
  18768. * 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).
  18769. */
  18770. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18771. var bInfo = this.getBoundingInfo();
  18772. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18773. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18774. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18775. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18776. return null;
  18777. }
  18778. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18779. };
  18780. /**
  18781. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18782. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18783. * 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.
  18784. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18785. * 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.
  18786. */
  18787. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18788. if (checkFace === void 0) { checkFace = false; }
  18789. if (facing === void 0) { facing = true; }
  18790. var world = this.getWorldMatrix();
  18791. var invMat = BABYLON.Tmp.Matrix[5];
  18792. world.invertToRef(invMat);
  18793. var invVect = BABYLON.Tmp.Vector3[8];
  18794. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18795. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18796. if (projected) {
  18797. // tranform the local computed projected vector to world coordinates
  18798. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18799. }
  18800. return closest;
  18801. };
  18802. /**
  18803. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18804. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18805. * 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.
  18806. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18807. * 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.
  18808. */
  18809. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18810. if (checkFace === void 0) { checkFace = false; }
  18811. if (facing === void 0) { facing = true; }
  18812. var closest = null;
  18813. var tmpx = 0.0;
  18814. var tmpy = 0.0;
  18815. var tmpz = 0.0;
  18816. var d = 0.0; // tmp dot facet normal * facet position
  18817. var t0 = 0.0;
  18818. var projx = 0.0;
  18819. var projy = 0.0;
  18820. var projz = 0.0;
  18821. // Get all the facets in the same partitioning block than (x, y, z)
  18822. var facetPositions = this.getFacetLocalPositions();
  18823. var facetNormals = this.getFacetLocalNormals();
  18824. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18825. if (!facetsInBlock) {
  18826. return null;
  18827. }
  18828. // Get the closest facet to (x, y, z)
  18829. var shortest = Number.MAX_VALUE; // init distance vars
  18830. var tmpDistance = shortest;
  18831. var fib; // current facet in the block
  18832. var norm; // current facet normal
  18833. var p0; // current facet barycenter position
  18834. // loop on all the facets in the current partitioning block
  18835. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18836. fib = facetsInBlock[idx];
  18837. norm = facetNormals[fib];
  18838. p0 = facetPositions[fib];
  18839. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18840. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18841. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18842. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18843. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18844. projx = x + norm.x * t0;
  18845. projy = y + norm.y * t0;
  18846. projz = z + norm.z * t0;
  18847. tmpx = projx - x;
  18848. tmpy = projy - y;
  18849. tmpz = projz - z;
  18850. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18851. if (tmpDistance < shortest) {
  18852. shortest = tmpDistance;
  18853. closest = fib;
  18854. if (projected) {
  18855. projected.x = projx;
  18856. projected.y = projy;
  18857. projected.z = projz;
  18858. }
  18859. }
  18860. }
  18861. }
  18862. return closest;
  18863. };
  18864. /**
  18865. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18866. */
  18867. AbstractMesh.prototype.getFacetDataParameters = function () {
  18868. return this._facetParameters;
  18869. };
  18870. /**
  18871. * Disables the feature FacetData and frees the related memory.
  18872. * Returns the AbstractMesh.
  18873. */
  18874. AbstractMesh.prototype.disableFacetData = function () {
  18875. if (this._facetDataEnabled) {
  18876. this._facetDataEnabled = false;
  18877. this._facetPositions = new Array();
  18878. this._facetNormals = new Array();
  18879. this._facetPartitioning = new Array();
  18880. this._facetParameters = null;
  18881. this._depthSortedIndices = new Uint32Array(0);
  18882. }
  18883. return this;
  18884. };
  18885. /**
  18886. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18887. * Returns the mesh.
  18888. */
  18889. AbstractMesh.prototype.updateIndices = function (indices) {
  18890. return this;
  18891. };
  18892. /**
  18893. * The mesh Geometry. Actually used by the Mesh object.
  18894. * Returns a blank geometry object.
  18895. */
  18896. /**
  18897. * Creates new normals data for the mesh.
  18898. * @param updatable.
  18899. */
  18900. AbstractMesh.prototype.createNormals = function (updatable) {
  18901. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18902. var indices = this.getIndices();
  18903. var normals;
  18904. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18905. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18906. }
  18907. else {
  18908. normals = [];
  18909. }
  18910. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18911. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18912. };
  18913. /**
  18914. * Align the mesh with a normal.
  18915. * Returns the mesh.
  18916. */
  18917. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18918. if (!upDirection) {
  18919. upDirection = BABYLON.Axis.Y;
  18920. }
  18921. var axisX = BABYLON.Tmp.Vector3[0];
  18922. var axisZ = BABYLON.Tmp.Vector3[1];
  18923. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18924. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18925. if (this.rotationQuaternion) {
  18926. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18927. }
  18928. else {
  18929. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18930. }
  18931. return this;
  18932. };
  18933. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18934. var engine = this.getEngine();
  18935. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18936. this._isOccluded = false;
  18937. return;
  18938. }
  18939. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18940. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18941. if (isOcclusionQueryAvailable) {
  18942. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18943. this._isOcclusionQueryInProgress = false;
  18944. this._occlusionInternalRetryCounter = 0;
  18945. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18946. }
  18947. else {
  18948. this._occlusionInternalRetryCounter++;
  18949. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18950. this._isOcclusionQueryInProgress = false;
  18951. this._occlusionInternalRetryCounter = 0;
  18952. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18953. // if strict continue the last state of the object.
  18954. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18955. }
  18956. else {
  18957. return;
  18958. }
  18959. }
  18960. }
  18961. var scene = this.getScene();
  18962. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18963. if (!this._occlusionQuery) {
  18964. this._occlusionQuery = engine.createQuery();
  18965. }
  18966. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18967. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18968. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18969. this._isOcclusionQueryInProgress = true;
  18970. };
  18971. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18972. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18973. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18974. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18975. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18976. return AbstractMesh;
  18977. }(BABYLON.TransformNode));
  18978. BABYLON.AbstractMesh = AbstractMesh;
  18979. })(BABYLON || (BABYLON = {}));
  18980. //# sourceMappingURL=babylon.abstractMesh.js.map
  18981. var BABYLON;
  18982. (function (BABYLON) {
  18983. /**
  18984. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18985. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18986. * 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.
  18987. */
  18988. var Light = /** @class */ (function (_super) {
  18989. __extends(Light, _super);
  18990. /**
  18991. * Creates a Light object in the scene.
  18992. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18993. * @param name The firendly name of the light
  18994. * @param scene The scene the light belongs too
  18995. */
  18996. function Light(name, scene) {
  18997. var _this = _super.call(this, name, scene) || this;
  18998. /**
  18999. * Diffuse gives the basic color to an object.
  19000. */
  19001. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19002. /**
  19003. * Specular produces a highlight color on an object.
  19004. * Note: This is note affecting PBR materials.
  19005. */
  19006. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19007. /**
  19008. * Strength of the light.
  19009. * Note: By default it is define in the framework own unit.
  19010. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19011. */
  19012. _this.intensity = 1.0;
  19013. /**
  19014. * Defines how far from the source the light is impacting in scene units.
  19015. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19016. */
  19017. _this.range = Number.MAX_VALUE;
  19018. /**
  19019. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19020. * of light.
  19021. */
  19022. _this._photometricScale = 1.0;
  19023. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19024. _this._radius = 0.00001;
  19025. /**
  19026. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19027. * exceeding the number allowed of the materials.
  19028. */
  19029. _this.renderPriority = 0;
  19030. /**
  19031. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19032. * the current shadow generator.
  19033. */
  19034. _this.shadowEnabled = true;
  19035. _this._excludeWithLayerMask = 0;
  19036. _this._includeOnlyWithLayerMask = 0;
  19037. _this._lightmapMode = 0;
  19038. /**
  19039. * @ignore Internal use only.
  19040. */
  19041. _this._excludedMeshesIds = new Array();
  19042. /**
  19043. * @ignore Internal use only.
  19044. */
  19045. _this._includedOnlyMeshesIds = new Array();
  19046. _this.getScene().addLight(_this);
  19047. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19048. _this._buildUniformLayout();
  19049. _this.includedOnlyMeshes = new Array();
  19050. _this.excludedMeshes = new Array();
  19051. _this._resyncMeshes();
  19052. return _this;
  19053. }
  19054. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19055. /**
  19056. * If every light affecting the material is in this lightmapMode,
  19057. * material.lightmapTexture adds or multiplies
  19058. * (depends on material.useLightmapAsShadowmap)
  19059. * after every other light calculations.
  19060. */
  19061. get: function () {
  19062. return Light._LIGHTMAP_DEFAULT;
  19063. },
  19064. enumerable: true,
  19065. configurable: true
  19066. });
  19067. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19068. /**
  19069. * material.lightmapTexture as only diffuse lighting from this light
  19070. * adds only specular lighting from this light
  19071. * adds dynamic shadows
  19072. */
  19073. get: function () {
  19074. return Light._LIGHTMAP_SPECULAR;
  19075. },
  19076. enumerable: true,
  19077. configurable: true
  19078. });
  19079. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19080. /**
  19081. * material.lightmapTexture as only lighting
  19082. * no light calculation from this light
  19083. * only adds dynamic shadows from this light
  19084. */
  19085. get: function () {
  19086. return Light._LIGHTMAP_SHADOWSONLY;
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19092. /**
  19093. * Each light type uses the default quantity according to its type:
  19094. * point/spot lights use luminous intensity
  19095. * directional lights use illuminance
  19096. */
  19097. get: function () {
  19098. return Light._INTENSITYMODE_AUTOMATIC;
  19099. },
  19100. enumerable: true,
  19101. configurable: true
  19102. });
  19103. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19104. /**
  19105. * lumen (lm)
  19106. */
  19107. get: function () {
  19108. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19109. },
  19110. enumerable: true,
  19111. configurable: true
  19112. });
  19113. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19114. /**
  19115. * candela (lm/sr)
  19116. */
  19117. get: function () {
  19118. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19124. /**
  19125. * lux (lm/m^2)
  19126. */
  19127. get: function () {
  19128. return Light._INTENSITYMODE_ILLUMINANCE;
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19134. /**
  19135. * nit (cd/m^2)
  19136. */
  19137. get: function () {
  19138. return Light._INTENSITYMODE_LUMINANCE;
  19139. },
  19140. enumerable: true,
  19141. configurable: true
  19142. });
  19143. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19144. /**
  19145. * Light type const id of the point light.
  19146. */
  19147. get: function () {
  19148. return Light._LIGHTTYPEID_POINTLIGHT;
  19149. },
  19150. enumerable: true,
  19151. configurable: true
  19152. });
  19153. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19154. /**
  19155. * Light type const id of the directional light.
  19156. */
  19157. get: function () {
  19158. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19159. },
  19160. enumerable: true,
  19161. configurable: true
  19162. });
  19163. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19164. /**
  19165. * Light type const id of the spot light.
  19166. */
  19167. get: function () {
  19168. return Light._LIGHTTYPEID_SPOTLIGHT;
  19169. },
  19170. enumerable: true,
  19171. configurable: true
  19172. });
  19173. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19174. /**
  19175. * Light type const id of the hemispheric light.
  19176. */
  19177. get: function () {
  19178. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19179. },
  19180. enumerable: true,
  19181. configurable: true
  19182. });
  19183. Object.defineProperty(Light.prototype, "intensityMode", {
  19184. /**
  19185. * Gets the photometric scale used to interpret the intensity.
  19186. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19187. */
  19188. get: function () {
  19189. return this._intensityMode;
  19190. },
  19191. /**
  19192. * Sets the photometric scale used to interpret the intensity.
  19193. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19194. */
  19195. set: function (value) {
  19196. this._intensityMode = value;
  19197. this._computePhotometricScale();
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. ;
  19203. ;
  19204. Object.defineProperty(Light.prototype, "radius", {
  19205. /**
  19206. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19207. */
  19208. get: function () {
  19209. return this._radius;
  19210. },
  19211. /**
  19212. * sets the light radius used by PBR Materials to simulate soft area lights.
  19213. */
  19214. set: function (value) {
  19215. this._radius = value;
  19216. this._computePhotometricScale();
  19217. },
  19218. enumerable: true,
  19219. configurable: true
  19220. });
  19221. ;
  19222. ;
  19223. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19224. /**
  19225. * Gets the only meshes impacted by this light.
  19226. */
  19227. get: function () {
  19228. return this._includedOnlyMeshes;
  19229. },
  19230. /**
  19231. * Sets the only meshes impacted by this light.
  19232. */
  19233. set: function (value) {
  19234. this._includedOnlyMeshes = value;
  19235. this._hookArrayForIncludedOnly(value);
  19236. },
  19237. enumerable: true,
  19238. configurable: true
  19239. });
  19240. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19241. /**
  19242. * Gets the meshes not impacted by this light.
  19243. */
  19244. get: function () {
  19245. return this._excludedMeshes;
  19246. },
  19247. /**
  19248. * Sets the meshes not impacted by this light.
  19249. */
  19250. set: function (value) {
  19251. this._excludedMeshes = value;
  19252. this._hookArrayForExcluded(value);
  19253. },
  19254. enumerable: true,
  19255. configurable: true
  19256. });
  19257. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19258. /**
  19259. * Gets the layer id use to find what meshes are not impacted by the light.
  19260. * Inactive if 0
  19261. */
  19262. get: function () {
  19263. return this._excludeWithLayerMask;
  19264. },
  19265. /**
  19266. * Sets the layer id use to find what meshes are not impacted by the light.
  19267. * Inactive if 0
  19268. */
  19269. set: function (value) {
  19270. this._excludeWithLayerMask = value;
  19271. this._resyncMeshes();
  19272. },
  19273. enumerable: true,
  19274. configurable: true
  19275. });
  19276. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19277. /**
  19278. * Gets the layer id use to find what meshes are impacted by the light.
  19279. * Inactive if 0
  19280. */
  19281. get: function () {
  19282. return this._includeOnlyWithLayerMask;
  19283. },
  19284. /**
  19285. * Sets the layer id use to find what meshes are impacted by the light.
  19286. * Inactive if 0
  19287. */
  19288. set: function (value) {
  19289. this._includeOnlyWithLayerMask = value;
  19290. this._resyncMeshes();
  19291. },
  19292. enumerable: true,
  19293. configurable: true
  19294. });
  19295. Object.defineProperty(Light.prototype, "lightmapMode", {
  19296. /**
  19297. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19298. */
  19299. get: function () {
  19300. return this._lightmapMode;
  19301. },
  19302. /**
  19303. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19304. */
  19305. set: function (value) {
  19306. if (this._lightmapMode === value) {
  19307. return;
  19308. }
  19309. this._lightmapMode = value;
  19310. this._markMeshesAsLightDirty();
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. /**
  19316. * Returns the string "Light".
  19317. * @returns the class name
  19318. */
  19319. Light.prototype.getClassName = function () {
  19320. return "Light";
  19321. };
  19322. /**
  19323. * Converts the light information to a readable string for debug purpose.
  19324. * @param fullDetails Supports for multiple levels of logging within scene loading
  19325. * @returns the human readable light info
  19326. */
  19327. Light.prototype.toString = function (fullDetails) {
  19328. var ret = "Name: " + this.name;
  19329. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19330. if (this.animations) {
  19331. for (var i = 0; i < this.animations.length; i++) {
  19332. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19333. }
  19334. }
  19335. if (fullDetails) {
  19336. }
  19337. return ret;
  19338. };
  19339. /**
  19340. * Set the enabled state of this node.
  19341. * @param value - the new enabled state
  19342. * @see isEnabled
  19343. */
  19344. Light.prototype.setEnabled = function (value) {
  19345. _super.prototype.setEnabled.call(this, value);
  19346. this._resyncMeshes();
  19347. };
  19348. /**
  19349. * Returns the Light associated shadow generator if any.
  19350. * @return the associated shadow generator.
  19351. */
  19352. Light.prototype.getShadowGenerator = function () {
  19353. return this._shadowGenerator;
  19354. };
  19355. /**
  19356. * Returns a Vector3, the absolute light position in the World.
  19357. * @returns the world space position of the light
  19358. */
  19359. Light.prototype.getAbsolutePosition = function () {
  19360. return BABYLON.Vector3.Zero();
  19361. };
  19362. /**
  19363. * Specifies if the light will affect the passed mesh.
  19364. * @param mesh The mesh to test against the light
  19365. * @return true the mesh is affected otherwise, false.
  19366. */
  19367. Light.prototype.canAffectMesh = function (mesh) {
  19368. if (!mesh) {
  19369. return true;
  19370. }
  19371. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19372. return false;
  19373. }
  19374. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19375. return false;
  19376. }
  19377. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19378. return false;
  19379. }
  19380. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19381. return false;
  19382. }
  19383. return true;
  19384. };
  19385. /**
  19386. * Computes and Returns the light World matrix.
  19387. * @returns the world matrix
  19388. */
  19389. Light.prototype.getWorldMatrix = function () {
  19390. this._currentRenderId = this.getScene().getRenderId();
  19391. var worldMatrix = this._getWorldMatrix();
  19392. if (this.parent && this.parent.getWorldMatrix) {
  19393. if (!this._parentedWorldMatrix) {
  19394. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19395. }
  19396. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19397. this._markSyncedWithParent();
  19398. return this._parentedWorldMatrix;
  19399. }
  19400. return worldMatrix;
  19401. };
  19402. /**
  19403. * Sort function to order lights for rendering.
  19404. * @param a First Light object to compare to second.
  19405. * @param b Second Light object to compare first.
  19406. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19407. */
  19408. Light.CompareLightsPriority = function (a, b) {
  19409. //shadow-casting lights have priority over non-shadow-casting lights
  19410. //the renderPrioirty is a secondary sort criterion
  19411. if (a.shadowEnabled !== b.shadowEnabled) {
  19412. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19413. }
  19414. return b.renderPriority - a.renderPriority;
  19415. };
  19416. /**
  19417. * Releases resources associated with this node.
  19418. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19419. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19420. */
  19421. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19422. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19423. if (this._shadowGenerator) {
  19424. this._shadowGenerator.dispose();
  19425. this._shadowGenerator = null;
  19426. }
  19427. // Animations
  19428. this.getScene().stopAnimation(this);
  19429. // Remove from meshes
  19430. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19431. var mesh = _a[_i];
  19432. mesh._removeLightSource(this);
  19433. }
  19434. this._uniformBuffer.dispose();
  19435. // Remove from scene
  19436. this.getScene().removeLight(this);
  19437. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19438. };
  19439. /**
  19440. * Returns the light type ID (integer).
  19441. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19442. */
  19443. Light.prototype.getTypeID = function () {
  19444. return 0;
  19445. };
  19446. /**
  19447. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19448. * @returns the scaled intensity in intensity mode unit
  19449. */
  19450. Light.prototype.getScaledIntensity = function () {
  19451. return this._photometricScale * this.intensity;
  19452. };
  19453. /**
  19454. * Returns a new Light object, named "name", from the current one.
  19455. * @param name The name of the cloned light
  19456. * @returns the new created light
  19457. */
  19458. Light.prototype.clone = function (name) {
  19459. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19460. if (!constructor) {
  19461. return null;
  19462. }
  19463. return BABYLON.SerializationHelper.Clone(constructor, this);
  19464. };
  19465. /**
  19466. * Serializes the current light into a Serialization object.
  19467. * @returns the serialized object.
  19468. */
  19469. Light.prototype.serialize = function () {
  19470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19471. // Type
  19472. serializationObject.type = this.getTypeID();
  19473. // Parent
  19474. if (this.parent) {
  19475. serializationObject.parentId = this.parent.id;
  19476. }
  19477. // Inclusion / exclusions
  19478. if (this.excludedMeshes.length > 0) {
  19479. serializationObject.excludedMeshesIds = [];
  19480. this.excludedMeshes.forEach(function (mesh) {
  19481. serializationObject.excludedMeshesIds.push(mesh.id);
  19482. });
  19483. }
  19484. if (this.includedOnlyMeshes.length > 0) {
  19485. serializationObject.includedOnlyMeshesIds = [];
  19486. this.includedOnlyMeshes.forEach(function (mesh) {
  19487. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19488. });
  19489. }
  19490. // Animations
  19491. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19492. serializationObject.ranges = this.serializeAnimationRanges();
  19493. return serializationObject;
  19494. };
  19495. /**
  19496. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19497. * This new light is named "name" and added to the passed scene.
  19498. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19499. * @param name The friendly name of the light
  19500. * @param scene The scene the new light will belong to
  19501. * @returns the constructor function
  19502. */
  19503. Light.GetConstructorFromName = function (type, name, scene) {
  19504. switch (type) {
  19505. case 0:
  19506. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19507. case 1:
  19508. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19509. case 2:
  19510. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19511. case 3:
  19512. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19513. }
  19514. return null;
  19515. };
  19516. /**
  19517. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19518. * @param parsedLight The JSON representation of the light
  19519. * @param scene The scene to create the parsed light in
  19520. * @returns the created light after parsing
  19521. */
  19522. Light.Parse = function (parsedLight, scene) {
  19523. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19524. if (!constructor) {
  19525. return null;
  19526. }
  19527. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19528. // Inclusion / exclusions
  19529. if (parsedLight.excludedMeshesIds) {
  19530. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19531. }
  19532. if (parsedLight.includedOnlyMeshesIds) {
  19533. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19534. }
  19535. // Parent
  19536. if (parsedLight.parentId) {
  19537. light._waitingParentId = parsedLight.parentId;
  19538. }
  19539. // Animations
  19540. if (parsedLight.animations) {
  19541. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19542. var parsedAnimation = parsedLight.animations[animationIndex];
  19543. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19544. }
  19545. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19546. }
  19547. if (parsedLight.autoAnimate) {
  19548. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19549. }
  19550. return light;
  19551. };
  19552. Light.prototype._hookArrayForExcluded = function (array) {
  19553. var _this = this;
  19554. var oldPush = array.push;
  19555. array.push = function () {
  19556. var items = [];
  19557. for (var _i = 0; _i < arguments.length; _i++) {
  19558. items[_i] = arguments[_i];
  19559. }
  19560. var result = oldPush.apply(array, items);
  19561. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19562. var item = items_1[_a];
  19563. item._resyncLighSource(_this);
  19564. }
  19565. return result;
  19566. };
  19567. var oldSplice = array.splice;
  19568. array.splice = function (index, deleteCount) {
  19569. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19570. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19571. var item = deleted_1[_i];
  19572. item._resyncLighSource(_this);
  19573. }
  19574. return deleted;
  19575. };
  19576. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19577. var item = array_1[_i];
  19578. item._resyncLighSource(this);
  19579. }
  19580. };
  19581. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19582. var _this = this;
  19583. var oldPush = array.push;
  19584. array.push = function () {
  19585. var items = [];
  19586. for (var _i = 0; _i < arguments.length; _i++) {
  19587. items[_i] = arguments[_i];
  19588. }
  19589. var result = oldPush.apply(array, items);
  19590. _this._resyncMeshes();
  19591. return result;
  19592. };
  19593. var oldSplice = array.splice;
  19594. array.splice = function (index, deleteCount) {
  19595. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19596. _this._resyncMeshes();
  19597. return deleted;
  19598. };
  19599. this._resyncMeshes();
  19600. };
  19601. Light.prototype._resyncMeshes = function () {
  19602. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19603. var mesh = _a[_i];
  19604. mesh._resyncLighSource(this);
  19605. }
  19606. };
  19607. /**
  19608. * Forces the meshes to update their light related information in their rendering used effects
  19609. * @ignore Internal Use Only
  19610. */
  19611. Light.prototype._markMeshesAsLightDirty = function () {
  19612. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19613. var mesh = _a[_i];
  19614. if (mesh._lightSources.indexOf(this) !== -1) {
  19615. mesh._markSubMeshesAsLightDirty();
  19616. }
  19617. }
  19618. };
  19619. /**
  19620. * Recomputes the cached photometric scale if needed.
  19621. */
  19622. Light.prototype._computePhotometricScale = function () {
  19623. this._photometricScale = this._getPhotometricScale();
  19624. this.getScene().resetCachedMaterial();
  19625. };
  19626. /**
  19627. * Returns the Photometric Scale according to the light type and intensity mode.
  19628. */
  19629. Light.prototype._getPhotometricScale = function () {
  19630. var photometricScale = 0.0;
  19631. var lightTypeID = this.getTypeID();
  19632. //get photometric mode
  19633. var photometricMode = this.intensityMode;
  19634. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19635. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19636. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19637. }
  19638. else {
  19639. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19640. }
  19641. }
  19642. //compute photometric scale
  19643. switch (lightTypeID) {
  19644. case Light.LIGHTTYPEID_POINTLIGHT:
  19645. case Light.LIGHTTYPEID_SPOTLIGHT:
  19646. switch (photometricMode) {
  19647. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19648. photometricScale = 1.0 / (4.0 * Math.PI);
  19649. break;
  19650. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19651. photometricScale = 1.0;
  19652. break;
  19653. case Light.INTENSITYMODE_LUMINANCE:
  19654. photometricScale = this.radius * this.radius;
  19655. break;
  19656. }
  19657. break;
  19658. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19659. switch (photometricMode) {
  19660. case Light.INTENSITYMODE_ILLUMINANCE:
  19661. photometricScale = 1.0;
  19662. break;
  19663. case Light.INTENSITYMODE_LUMINANCE:
  19664. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19665. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19666. var apexAngleRadians = this.radius;
  19667. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19668. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19669. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19670. photometricScale = solidAngle;
  19671. break;
  19672. }
  19673. break;
  19674. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19675. // No fall off in hemisperic light.
  19676. photometricScale = 1.0;
  19677. break;
  19678. }
  19679. return photometricScale;
  19680. };
  19681. /**
  19682. * Reorder the light in the scene according to their defined priority.
  19683. * @ignore Internal Use Only
  19684. */
  19685. Light.prototype._reorderLightsInScene = function () {
  19686. var scene = this.getScene();
  19687. if (this._renderPriority != 0) {
  19688. scene.requireLightSorting = true;
  19689. }
  19690. this.getScene().sortLightsByPriority();
  19691. };
  19692. //lightmapMode Consts
  19693. Light._LIGHTMAP_DEFAULT = 0;
  19694. Light._LIGHTMAP_SPECULAR = 1;
  19695. Light._LIGHTMAP_SHADOWSONLY = 2;
  19696. // Intensity Mode Consts
  19697. Light._INTENSITYMODE_AUTOMATIC = 0;
  19698. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19699. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19700. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19701. Light._INTENSITYMODE_LUMINANCE = 4;
  19702. // Light types ids const.
  19703. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19704. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19705. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19706. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19707. __decorate([
  19708. BABYLON.serializeAsColor3()
  19709. ], Light.prototype, "diffuse", void 0);
  19710. __decorate([
  19711. BABYLON.serializeAsColor3()
  19712. ], Light.prototype, "specular", void 0);
  19713. __decorate([
  19714. BABYLON.serialize()
  19715. ], Light.prototype, "intensity", void 0);
  19716. __decorate([
  19717. BABYLON.serialize()
  19718. ], Light.prototype, "range", void 0);
  19719. __decorate([
  19720. BABYLON.serialize()
  19721. ], Light.prototype, "intensityMode", null);
  19722. __decorate([
  19723. BABYLON.serialize()
  19724. ], Light.prototype, "radius", null);
  19725. __decorate([
  19726. BABYLON.serialize()
  19727. ], Light.prototype, "_renderPriority", void 0);
  19728. __decorate([
  19729. BABYLON.expandToProperty("_reorderLightsInScene")
  19730. ], Light.prototype, "renderPriority", void 0);
  19731. __decorate([
  19732. BABYLON.serialize()
  19733. ], Light.prototype, "shadowEnabled", void 0);
  19734. __decorate([
  19735. BABYLON.serialize("excludeWithLayerMask")
  19736. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19737. __decorate([
  19738. BABYLON.serialize("includeOnlyWithLayerMask")
  19739. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19740. __decorate([
  19741. BABYLON.serialize("lightmapMode")
  19742. ], Light.prototype, "_lightmapMode", void 0);
  19743. return Light;
  19744. }(BABYLON.Node));
  19745. BABYLON.Light = Light;
  19746. })(BABYLON || (BABYLON = {}));
  19747. //# sourceMappingURL=babylon.light.js.map
  19748. var BABYLON;
  19749. (function (BABYLON) {
  19750. var Camera = /** @class */ (function (_super) {
  19751. __extends(Camera, _super);
  19752. function Camera(name, position, scene) {
  19753. var _this = _super.call(this, name, scene) || this;
  19754. /**
  19755. * The vector the camera should consider as up.
  19756. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19757. */
  19758. _this.upVector = BABYLON.Vector3.Up();
  19759. _this.orthoLeft = null;
  19760. _this.orthoRight = null;
  19761. _this.orthoBottom = null;
  19762. _this.orthoTop = null;
  19763. /**
  19764. * FOV is set in Radians. (default is 0.8)
  19765. */
  19766. _this.fov = 0.8;
  19767. _this.minZ = 1;
  19768. _this.maxZ = 10000.0;
  19769. _this.inertia = 0.9;
  19770. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19771. _this.isIntermediate = false;
  19772. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19773. /**
  19774. * Restricts the camera to viewing objects with the same layerMask.
  19775. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19776. */
  19777. _this.layerMask = 0x0FFFFFFF;
  19778. /**
  19779. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19780. */
  19781. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19782. // Camera rig members
  19783. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19784. _this._rigCameras = new Array();
  19785. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19786. _this._skipRendering = false;
  19787. _this.customRenderTargets = new Array();
  19788. // Observables
  19789. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19790. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19791. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19792. _this.onRestoreStateObservable = new BABYLON.Observable();
  19793. // Cache
  19794. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19795. _this._projectionMatrix = new BABYLON.Matrix();
  19796. _this._doNotComputeProjectionMatrix = false;
  19797. _this._postProcesses = new Array();
  19798. _this._transformMatrix = BABYLON.Matrix.Zero();
  19799. _this._activeMeshes = new BABYLON.SmartArray(256);
  19800. _this._globalPosition = BABYLON.Vector3.Zero();
  19801. _this._refreshFrustumPlanes = true;
  19802. _this.getScene().addCamera(_this);
  19803. if (!_this.getScene().activeCamera) {
  19804. _this.getScene().activeCamera = _this;
  19805. }
  19806. _this.position = position;
  19807. return _this;
  19808. }
  19809. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19810. get: function () {
  19811. return Camera._PERSPECTIVE_CAMERA;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19817. get: function () {
  19818. return Camera._ORTHOGRAPHIC_CAMERA;
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19824. /**
  19825. * This is the default FOV mode for perspective cameras.
  19826. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19827. *
  19828. */
  19829. get: function () {
  19830. return Camera._FOVMODE_VERTICAL_FIXED;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19836. /**
  19837. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19838. *
  19839. */
  19840. get: function () {
  19841. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19847. get: function () {
  19848. return Camera._RIG_MODE_NONE;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19854. get: function () {
  19855. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19861. get: function () {
  19862. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19868. get: function () {
  19869. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19875. get: function () {
  19876. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19882. get: function () {
  19883. return Camera._RIG_MODE_VR;
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19889. get: function () {
  19890. return Camera._RIG_MODE_WEBVR;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. /**
  19896. * Store current camera state (fov, position, etc..)
  19897. */
  19898. Camera.prototype.storeState = function () {
  19899. this._stateStored = true;
  19900. this._storedFov = this.fov;
  19901. return this;
  19902. };
  19903. /**
  19904. * Restores the camera state values if it has been stored. You must call storeState() first
  19905. */
  19906. Camera.prototype._restoreStateValues = function () {
  19907. if (!this._stateStored) {
  19908. return false;
  19909. }
  19910. this.fov = this._storedFov;
  19911. return true;
  19912. };
  19913. /**
  19914. * Restored camera state. You must call storeState() first
  19915. */
  19916. Camera.prototype.restoreState = function () {
  19917. if (this._restoreStateValues()) {
  19918. this.onRestoreStateObservable.notifyObservers(this);
  19919. return true;
  19920. }
  19921. return false;
  19922. };
  19923. Camera.prototype.getClassName = function () {
  19924. return "Camera";
  19925. };
  19926. /**
  19927. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19928. */
  19929. Camera.prototype.toString = function (fullDetails) {
  19930. var ret = "Name: " + this.name;
  19931. ret += ", type: " + this.getClassName();
  19932. if (this.animations) {
  19933. for (var i = 0; i < this.animations.length; i++) {
  19934. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19935. }
  19936. }
  19937. if (fullDetails) {
  19938. }
  19939. return ret;
  19940. };
  19941. Object.defineProperty(Camera.prototype, "globalPosition", {
  19942. get: function () {
  19943. return this._globalPosition;
  19944. },
  19945. enumerable: true,
  19946. configurable: true
  19947. });
  19948. Camera.prototype.getActiveMeshes = function () {
  19949. return this._activeMeshes;
  19950. };
  19951. Camera.prototype.isActiveMesh = function (mesh) {
  19952. return (this._activeMeshes.indexOf(mesh) !== -1);
  19953. };
  19954. //Cache
  19955. Camera.prototype._initCache = function () {
  19956. _super.prototype._initCache.call(this);
  19957. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19958. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19959. this._cache.mode = undefined;
  19960. this._cache.minZ = undefined;
  19961. this._cache.maxZ = undefined;
  19962. this._cache.fov = undefined;
  19963. this._cache.fovMode = undefined;
  19964. this._cache.aspectRatio = undefined;
  19965. this._cache.orthoLeft = undefined;
  19966. this._cache.orthoRight = undefined;
  19967. this._cache.orthoBottom = undefined;
  19968. this._cache.orthoTop = undefined;
  19969. this._cache.renderWidth = undefined;
  19970. this._cache.renderHeight = undefined;
  19971. };
  19972. Camera.prototype._updateCache = function (ignoreParentClass) {
  19973. if (!ignoreParentClass) {
  19974. _super.prototype._updateCache.call(this);
  19975. }
  19976. this._cache.position.copyFrom(this.position);
  19977. this._cache.upVector.copyFrom(this.upVector);
  19978. };
  19979. // Synchronized
  19980. Camera.prototype._isSynchronized = function () {
  19981. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19982. };
  19983. Camera.prototype._isSynchronizedViewMatrix = function () {
  19984. if (!_super.prototype._isSynchronized.call(this))
  19985. return false;
  19986. return this._cache.position.equals(this.position)
  19987. && this._cache.upVector.equals(this.upVector)
  19988. && this.isSynchronizedWithParent();
  19989. };
  19990. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19991. var check = this._cache.mode === this.mode
  19992. && this._cache.minZ === this.minZ
  19993. && this._cache.maxZ === this.maxZ;
  19994. if (!check) {
  19995. return false;
  19996. }
  19997. var engine = this.getEngine();
  19998. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19999. check = this._cache.fov === this.fov
  20000. && this._cache.fovMode === this.fovMode
  20001. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20002. }
  20003. else {
  20004. check = this._cache.orthoLeft === this.orthoLeft
  20005. && this._cache.orthoRight === this.orthoRight
  20006. && this._cache.orthoBottom === this.orthoBottom
  20007. && this._cache.orthoTop === this.orthoTop
  20008. && this._cache.renderWidth === engine.getRenderWidth()
  20009. && this._cache.renderHeight === engine.getRenderHeight();
  20010. }
  20011. return check;
  20012. };
  20013. // Controls
  20014. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20015. };
  20016. Camera.prototype.detachControl = function (element) {
  20017. };
  20018. Camera.prototype.update = function () {
  20019. this._checkInputs();
  20020. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20021. this._updateRigCameras();
  20022. }
  20023. };
  20024. Camera.prototype._checkInputs = function () {
  20025. this.onAfterCheckInputsObservable.notifyObservers(this);
  20026. };
  20027. Object.defineProperty(Camera.prototype, "rigCameras", {
  20028. get: function () {
  20029. return this._rigCameras;
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20035. get: function () {
  20036. return this._rigPostProcess;
  20037. },
  20038. enumerable: true,
  20039. configurable: true
  20040. });
  20041. /**
  20042. * Internal, gets the first post proces.
  20043. * @returns the first post process to be run on this camera.
  20044. */
  20045. Camera.prototype._getFirstPostProcess = function () {
  20046. for (var pp in this._postProcesses) {
  20047. if (this._postProcesses[pp] !== null) {
  20048. return this._postProcesses[pp];
  20049. }
  20050. }
  20051. return null;
  20052. };
  20053. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20054. // invalidate framebuffer
  20055. var firstPostProcess = this._getFirstPostProcess();
  20056. if (firstPostProcess) {
  20057. firstPostProcess.markTextureDirty();
  20058. }
  20059. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20060. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20061. var cam = this._rigCameras[i];
  20062. var rigPostProcess = cam._rigPostProcess;
  20063. // for VR rig, there does not have to be a post process
  20064. if (rigPostProcess) {
  20065. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20066. if (isPass) {
  20067. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20068. cam.isIntermediate = this._postProcesses.length === 0;
  20069. }
  20070. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20071. rigPostProcess.markTextureDirty();
  20072. }
  20073. else {
  20074. cam._postProcesses = this._postProcesses.slice(0);
  20075. }
  20076. }
  20077. };
  20078. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20079. if (insertAt === void 0) { insertAt = null; }
  20080. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20081. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20082. return 0;
  20083. }
  20084. if (insertAt == null || insertAt < 0) {
  20085. this._postProcesses.push(postProcess);
  20086. }
  20087. else if (this._postProcesses[insertAt] === null) {
  20088. this._postProcesses[insertAt] = postProcess;
  20089. }
  20090. else {
  20091. this._postProcesses.splice(insertAt, 0, postProcess);
  20092. }
  20093. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20094. return this._postProcesses.indexOf(postProcess);
  20095. };
  20096. Camera.prototype.detachPostProcess = function (postProcess) {
  20097. var idx = this._postProcesses.indexOf(postProcess);
  20098. if (idx !== -1) {
  20099. this._postProcesses[idx] = null;
  20100. }
  20101. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20102. };
  20103. Camera.prototype.getWorldMatrix = function () {
  20104. if (!this._worldMatrix) {
  20105. this._worldMatrix = BABYLON.Matrix.Identity();
  20106. }
  20107. var viewMatrix = this.getViewMatrix();
  20108. viewMatrix.invertToRef(this._worldMatrix);
  20109. return this._worldMatrix;
  20110. };
  20111. Camera.prototype._getViewMatrix = function () {
  20112. return BABYLON.Matrix.Identity();
  20113. };
  20114. Camera.prototype.getViewMatrix = function (force) {
  20115. if (!force && this._isSynchronizedViewMatrix()) {
  20116. return this._computedViewMatrix;
  20117. }
  20118. this.updateCache();
  20119. this._computedViewMatrix = this._getViewMatrix();
  20120. this._currentRenderId = this.getScene().getRenderId();
  20121. this._refreshFrustumPlanes = true;
  20122. if (!this.parent || !this.parent.getWorldMatrix) {
  20123. this._globalPosition.copyFrom(this.position);
  20124. }
  20125. else {
  20126. if (!this._worldMatrix) {
  20127. this._worldMatrix = BABYLON.Matrix.Identity();
  20128. }
  20129. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20130. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20131. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20132. this._computedViewMatrix.invert();
  20133. this._markSyncedWithParent();
  20134. }
  20135. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20136. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20137. }
  20138. this.onViewMatrixChangedObservable.notifyObservers(this);
  20139. return this._computedViewMatrix;
  20140. };
  20141. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20142. this._doNotComputeProjectionMatrix = true;
  20143. if (projection !== undefined) {
  20144. this._projectionMatrix = projection;
  20145. }
  20146. };
  20147. ;
  20148. Camera.prototype.unfreezeProjectionMatrix = function () {
  20149. this._doNotComputeProjectionMatrix = false;
  20150. };
  20151. ;
  20152. Camera.prototype.getProjectionMatrix = function (force) {
  20153. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20154. return this._projectionMatrix;
  20155. }
  20156. // Cache
  20157. this._cache.mode = this.mode;
  20158. this._cache.minZ = this.minZ;
  20159. this._cache.maxZ = this.maxZ;
  20160. // Matrix
  20161. this._refreshFrustumPlanes = true;
  20162. var engine = this.getEngine();
  20163. var scene = this.getScene();
  20164. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20165. this._cache.fov = this.fov;
  20166. this._cache.fovMode = this.fovMode;
  20167. this._cache.aspectRatio = engine.getAspectRatio(this);
  20168. if (this.minZ <= 0) {
  20169. this.minZ = 0.1;
  20170. }
  20171. if (scene.useRightHandedSystem) {
  20172. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20173. }
  20174. else {
  20175. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20176. }
  20177. }
  20178. else {
  20179. var halfWidth = engine.getRenderWidth() / 2.0;
  20180. var halfHeight = engine.getRenderHeight() / 2.0;
  20181. if (scene.useRightHandedSystem) {
  20182. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20183. }
  20184. else {
  20185. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20186. }
  20187. this._cache.orthoLeft = this.orthoLeft;
  20188. this._cache.orthoRight = this.orthoRight;
  20189. this._cache.orthoBottom = this.orthoBottom;
  20190. this._cache.orthoTop = this.orthoTop;
  20191. this._cache.renderWidth = engine.getRenderWidth();
  20192. this._cache.renderHeight = engine.getRenderHeight();
  20193. }
  20194. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20195. return this._projectionMatrix;
  20196. };
  20197. Camera.prototype.getTranformationMatrix = function () {
  20198. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20199. return this._transformMatrix;
  20200. };
  20201. Camera.prototype.updateFrustumPlanes = function () {
  20202. if (!this._refreshFrustumPlanes) {
  20203. return;
  20204. }
  20205. this.getTranformationMatrix();
  20206. if (!this._frustumPlanes) {
  20207. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20208. }
  20209. else {
  20210. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20211. }
  20212. this._refreshFrustumPlanes = false;
  20213. };
  20214. Camera.prototype.isInFrustum = function (target) {
  20215. this.updateFrustumPlanes();
  20216. return target.isInFrustum(this._frustumPlanes);
  20217. };
  20218. Camera.prototype.isCompletelyInFrustum = function (target) {
  20219. this.updateFrustumPlanes();
  20220. return target.isCompletelyInFrustum(this._frustumPlanes);
  20221. };
  20222. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20223. if (length === void 0) { length = 100; }
  20224. if (!transform) {
  20225. transform = this.getWorldMatrix();
  20226. }
  20227. if (!origin) {
  20228. origin = this.position;
  20229. }
  20230. var forward = new BABYLON.Vector3(0, 0, 1);
  20231. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20232. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20233. return new BABYLON.Ray(origin, direction, length);
  20234. };
  20235. /**
  20236. * Releases resources associated with this node.
  20237. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20238. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20239. */
  20240. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20241. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20242. // Observables
  20243. this.onViewMatrixChangedObservable.clear();
  20244. this.onProjectionMatrixChangedObservable.clear();
  20245. this.onAfterCheckInputsObservable.clear();
  20246. this.onRestoreStateObservable.clear();
  20247. // Inputs
  20248. if (this.inputs) {
  20249. this.inputs.clear();
  20250. }
  20251. // Animations
  20252. this.getScene().stopAnimation(this);
  20253. // Remove from scene
  20254. this.getScene().removeCamera(this);
  20255. while (this._rigCameras.length > 0) {
  20256. var camera = this._rigCameras.pop();
  20257. if (camera) {
  20258. camera.dispose();
  20259. }
  20260. }
  20261. // Postprocesses
  20262. if (this._rigPostProcess) {
  20263. this._rigPostProcess.dispose(this);
  20264. this._rigPostProcess = null;
  20265. this._postProcesses = [];
  20266. }
  20267. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20268. this._rigPostProcess = null;
  20269. this._postProcesses = [];
  20270. }
  20271. else {
  20272. var i = this._postProcesses.length;
  20273. while (--i >= 0) {
  20274. var postProcess = this._postProcesses[i];
  20275. if (postProcess) {
  20276. postProcess.dispose(this);
  20277. }
  20278. }
  20279. }
  20280. // Render targets
  20281. var i = this.customRenderTargets.length;
  20282. while (--i >= 0) {
  20283. this.customRenderTargets[i].dispose();
  20284. }
  20285. this.customRenderTargets = [];
  20286. // Active Meshes
  20287. this._activeMeshes.dispose();
  20288. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20289. };
  20290. Object.defineProperty(Camera.prototype, "leftCamera", {
  20291. // ---- Camera rigs section ----
  20292. get: function () {
  20293. if (this._rigCameras.length < 1) {
  20294. return null;
  20295. }
  20296. return this._rigCameras[0];
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(Camera.prototype, "rightCamera", {
  20302. get: function () {
  20303. if (this._rigCameras.length < 2) {
  20304. return null;
  20305. }
  20306. return this._rigCameras[1];
  20307. },
  20308. enumerable: true,
  20309. configurable: true
  20310. });
  20311. Camera.prototype.getLeftTarget = function () {
  20312. if (this._rigCameras.length < 1) {
  20313. return null;
  20314. }
  20315. return this._rigCameras[0].getTarget();
  20316. };
  20317. Camera.prototype.getRightTarget = function () {
  20318. if (this._rigCameras.length < 2) {
  20319. return null;
  20320. }
  20321. return this._rigCameras[1].getTarget();
  20322. };
  20323. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20324. if (this.cameraRigMode === mode) {
  20325. return;
  20326. }
  20327. while (this._rigCameras.length > 0) {
  20328. var camera = this._rigCameras.pop();
  20329. if (camera) {
  20330. camera.dispose();
  20331. }
  20332. }
  20333. this.cameraRigMode = mode;
  20334. this._cameraRigParams = {};
  20335. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20336. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20337. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20338. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20339. // create the rig cameras, unless none
  20340. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20341. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20342. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20343. if (leftCamera && rightCamera) {
  20344. this._rigCameras.push(leftCamera);
  20345. this._rigCameras.push(rightCamera);
  20346. }
  20347. }
  20348. switch (this.cameraRigMode) {
  20349. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20350. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20351. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20352. break;
  20353. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20354. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20355. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20356. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20357. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20358. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20359. break;
  20360. case Camera.RIG_MODE_VR:
  20361. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20362. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20363. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20364. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20365. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20366. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20367. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20368. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20369. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20370. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20371. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20372. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20373. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20374. if (metrics.compensateDistortion) {
  20375. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20376. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20377. }
  20378. break;
  20379. case Camera.RIG_MODE_WEBVR:
  20380. if (rigParams.vrDisplay) {
  20381. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20382. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20383. //Left eye
  20384. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20385. this._rigCameras[0].setCameraRigParameter("left", true);
  20386. //leaving this for future reference
  20387. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20388. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20389. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20390. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20391. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20392. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20393. this._rigCameras[0].parent = this;
  20394. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20395. //Right eye
  20396. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20397. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20398. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20399. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20400. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20401. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20402. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20403. this._rigCameras[1].parent = this;
  20404. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20405. if (Camera.UseAlternateWebVRRendering) {
  20406. this._rigCameras[1]._skipRendering = true;
  20407. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20408. }
  20409. }
  20410. break;
  20411. }
  20412. this._cascadePostProcessesToRigCams();
  20413. this.update();
  20414. };
  20415. Camera.prototype._getVRProjectionMatrix = function () {
  20416. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20417. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20418. return this._projectionMatrix;
  20419. };
  20420. Camera.prototype._updateCameraRotationMatrix = function () {
  20421. //Here for WebVR
  20422. };
  20423. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20424. //Here for WebVR
  20425. };
  20426. /**
  20427. * This function MUST be overwritten by the different WebVR cameras available.
  20428. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20429. */
  20430. Camera.prototype._getWebVRProjectionMatrix = function () {
  20431. return BABYLON.Matrix.Identity();
  20432. };
  20433. /**
  20434. * This function MUST be overwritten by the different WebVR cameras available.
  20435. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20436. */
  20437. Camera.prototype._getWebVRViewMatrix = function () {
  20438. return BABYLON.Matrix.Identity();
  20439. };
  20440. Camera.prototype.setCameraRigParameter = function (name, value) {
  20441. if (!this._cameraRigParams) {
  20442. this._cameraRigParams = {};
  20443. }
  20444. this._cameraRigParams[name] = value;
  20445. //provisionnally:
  20446. if (name === "interaxialDistance") {
  20447. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20448. }
  20449. };
  20450. /**
  20451. * needs to be overridden by children so sub has required properties to be copied
  20452. */
  20453. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20454. return null;
  20455. };
  20456. /**
  20457. * May need to be overridden by children
  20458. */
  20459. Camera.prototype._updateRigCameras = function () {
  20460. for (var i = 0; i < this._rigCameras.length; i++) {
  20461. this._rigCameras[i].minZ = this.minZ;
  20462. this._rigCameras[i].maxZ = this.maxZ;
  20463. this._rigCameras[i].fov = this.fov;
  20464. }
  20465. // only update viewport when ANAGLYPH
  20466. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20467. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20468. }
  20469. };
  20470. Camera.prototype._setupInputs = function () {
  20471. };
  20472. Camera.prototype.serialize = function () {
  20473. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20474. // Type
  20475. serializationObject.type = this.getClassName();
  20476. // Parent
  20477. if (this.parent) {
  20478. serializationObject.parentId = this.parent.id;
  20479. }
  20480. if (this.inputs) {
  20481. this.inputs.serialize(serializationObject);
  20482. }
  20483. // Animations
  20484. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20485. serializationObject.ranges = this.serializeAnimationRanges();
  20486. return serializationObject;
  20487. };
  20488. Camera.prototype.clone = function (name) {
  20489. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20490. };
  20491. Camera.prototype.getDirection = function (localAxis) {
  20492. var result = BABYLON.Vector3.Zero();
  20493. this.getDirectionToRef(localAxis, result);
  20494. return result;
  20495. };
  20496. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20497. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20498. };
  20499. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20500. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20501. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20502. switch (type) {
  20503. case "ArcRotateCamera":
  20504. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20505. case "DeviceOrientationCamera":
  20506. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20507. case "FollowCamera":
  20508. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20509. case "ArcFollowCamera":
  20510. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20511. case "GamepadCamera":
  20512. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20513. case "TouchCamera":
  20514. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20515. case "VirtualJoysticksCamera":
  20516. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20517. case "WebVRFreeCamera":
  20518. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20519. case "WebVRGamepadCamera":
  20520. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20521. case "VRDeviceOrientationFreeCamera":
  20522. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20523. case "VRDeviceOrientationGamepadCamera":
  20524. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20525. case "AnaglyphArcRotateCamera":
  20526. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20527. case "AnaglyphFreeCamera":
  20528. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20529. case "AnaglyphGamepadCamera":
  20530. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20531. case "AnaglyphUniversalCamera":
  20532. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20533. case "StereoscopicArcRotateCamera":
  20534. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20535. case "StereoscopicFreeCamera":
  20536. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20537. case "StereoscopicGamepadCamera":
  20538. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20539. case "StereoscopicUniversalCamera":
  20540. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20541. case "FreeCamera":// Forcing Universal here
  20542. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20543. default:// Universal Camera is the default value
  20544. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20545. }
  20546. };
  20547. Camera.prototype.computeWorldMatrix = function () {
  20548. return this.getWorldMatrix();
  20549. };
  20550. Camera.Parse = function (parsedCamera, scene) {
  20551. var type = parsedCamera.type;
  20552. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20553. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20554. // Parent
  20555. if (parsedCamera.parentId) {
  20556. camera._waitingParentId = parsedCamera.parentId;
  20557. }
  20558. //If camera has an input manager, let it parse inputs settings
  20559. if (camera.inputs) {
  20560. camera.inputs.parse(parsedCamera);
  20561. camera._setupInputs();
  20562. }
  20563. if (camera.setPosition) {
  20564. camera.position.copyFromFloats(0, 0, 0);
  20565. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20566. }
  20567. // Target
  20568. if (parsedCamera.target) {
  20569. if (camera.setTarget) {
  20570. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20571. }
  20572. }
  20573. // Apply 3d rig, when found
  20574. if (parsedCamera.cameraRigMode) {
  20575. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20576. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20577. }
  20578. // Animations
  20579. if (parsedCamera.animations) {
  20580. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20581. var parsedAnimation = parsedCamera.animations[animationIndex];
  20582. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20583. }
  20584. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20585. }
  20586. if (parsedCamera.autoAnimate) {
  20587. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20588. }
  20589. return camera;
  20590. };
  20591. // Statics
  20592. Camera._PERSPECTIVE_CAMERA = 0;
  20593. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20594. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20595. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20596. Camera._RIG_MODE_NONE = 0;
  20597. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20598. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20599. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20600. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20601. Camera._RIG_MODE_VR = 20;
  20602. Camera._RIG_MODE_WEBVR = 21;
  20603. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20604. Camera.UseAlternateWebVRRendering = false;
  20605. __decorate([
  20606. BABYLON.serializeAsVector3()
  20607. ], Camera.prototype, "position", void 0);
  20608. __decorate([
  20609. BABYLON.serializeAsVector3()
  20610. ], Camera.prototype, "upVector", void 0);
  20611. __decorate([
  20612. BABYLON.serialize()
  20613. ], Camera.prototype, "orthoLeft", void 0);
  20614. __decorate([
  20615. BABYLON.serialize()
  20616. ], Camera.prototype, "orthoRight", void 0);
  20617. __decorate([
  20618. BABYLON.serialize()
  20619. ], Camera.prototype, "orthoBottom", void 0);
  20620. __decorate([
  20621. BABYLON.serialize()
  20622. ], Camera.prototype, "orthoTop", void 0);
  20623. __decorate([
  20624. BABYLON.serialize()
  20625. ], Camera.prototype, "fov", void 0);
  20626. __decorate([
  20627. BABYLON.serialize()
  20628. ], Camera.prototype, "minZ", void 0);
  20629. __decorate([
  20630. BABYLON.serialize()
  20631. ], Camera.prototype, "maxZ", void 0);
  20632. __decorate([
  20633. BABYLON.serialize()
  20634. ], Camera.prototype, "inertia", void 0);
  20635. __decorate([
  20636. BABYLON.serialize()
  20637. ], Camera.prototype, "mode", void 0);
  20638. __decorate([
  20639. BABYLON.serialize()
  20640. ], Camera.prototype, "layerMask", void 0);
  20641. __decorate([
  20642. BABYLON.serialize()
  20643. ], Camera.prototype, "fovMode", void 0);
  20644. __decorate([
  20645. BABYLON.serialize()
  20646. ], Camera.prototype, "cameraRigMode", void 0);
  20647. __decorate([
  20648. BABYLON.serialize()
  20649. ], Camera.prototype, "interaxialDistance", void 0);
  20650. __decorate([
  20651. BABYLON.serialize()
  20652. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20653. return Camera;
  20654. }(BABYLON.Node));
  20655. BABYLON.Camera = Camera;
  20656. })(BABYLON || (BABYLON = {}));
  20657. //# sourceMappingURL=babylon.camera.js.map
  20658. var BABYLON;
  20659. (function (BABYLON) {
  20660. var RenderingManager = /** @class */ (function () {
  20661. function RenderingManager(scene) {
  20662. this._renderingGroups = new Array();
  20663. this._autoClearDepthStencil = {};
  20664. this._customOpaqueSortCompareFn = {};
  20665. this._customAlphaTestSortCompareFn = {};
  20666. this._customTransparentSortCompareFn = {};
  20667. this._renderinGroupInfo = null;
  20668. this._scene = scene;
  20669. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20670. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20671. }
  20672. }
  20673. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20674. if (depth === void 0) { depth = true; }
  20675. if (stencil === void 0) { stencil = true; }
  20676. if (this._depthStencilBufferAlreadyCleaned) {
  20677. return;
  20678. }
  20679. this._scene.getEngine().clear(null, false, depth, stencil);
  20680. this._depthStencilBufferAlreadyCleaned = true;
  20681. };
  20682. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20683. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20684. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20685. var info = null;
  20686. if (observable) {
  20687. if (!this._renderinGroupInfo) {
  20688. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20689. }
  20690. info = this._renderinGroupInfo;
  20691. info.scene = this._scene;
  20692. info.camera = this._scene.activeCamera;
  20693. }
  20694. // Dispatch sprites
  20695. if (renderSprites) {
  20696. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20697. var manager = this._scene.spriteManagers[index];
  20698. this.dispatchSprites(manager);
  20699. }
  20700. }
  20701. // Render
  20702. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20703. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20704. var renderingGroup = this._renderingGroups[index];
  20705. if (!renderingGroup && !observable)
  20706. continue;
  20707. var renderingGroupMask = 0;
  20708. // Fire PRECLEAR stage
  20709. if (observable && info) {
  20710. renderingGroupMask = Math.pow(2, index);
  20711. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20712. info.renderingGroupId = index;
  20713. observable.notifyObservers(info, renderingGroupMask);
  20714. }
  20715. // Clear depth/stencil if needed
  20716. if (RenderingManager.AUTOCLEAR) {
  20717. var autoClear = this._autoClearDepthStencil[index];
  20718. if (autoClear && autoClear.autoClear) {
  20719. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20720. }
  20721. }
  20722. if (observable && info) {
  20723. // Fire PREOPAQUE stage
  20724. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20725. observable.notifyObservers(info, renderingGroupMask);
  20726. // Fire PRETRANSPARENT stage
  20727. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20728. observable.notifyObservers(info, renderingGroupMask);
  20729. }
  20730. if (renderingGroup)
  20731. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20732. // Fire POSTTRANSPARENT stage
  20733. if (observable && info) {
  20734. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20735. observable.notifyObservers(info, renderingGroupMask);
  20736. }
  20737. }
  20738. };
  20739. RenderingManager.prototype.reset = function () {
  20740. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20741. var renderingGroup = this._renderingGroups[index];
  20742. if (renderingGroup) {
  20743. renderingGroup.prepare();
  20744. }
  20745. }
  20746. };
  20747. RenderingManager.prototype.dispose = function () {
  20748. this.freeRenderingGroups();
  20749. this._renderingGroups.length = 0;
  20750. };
  20751. /**
  20752. * Clear the info related to rendering groups preventing retention points during dispose.
  20753. */
  20754. RenderingManager.prototype.freeRenderingGroups = function () {
  20755. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20756. var renderingGroup = this._renderingGroups[index];
  20757. if (renderingGroup) {
  20758. renderingGroup.dispose();
  20759. }
  20760. }
  20761. };
  20762. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20763. if (this._renderingGroups[renderingGroupId] === undefined) {
  20764. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20765. }
  20766. };
  20767. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20768. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20769. this._prepareRenderingGroup(renderingGroupId);
  20770. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20771. };
  20772. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20773. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20774. this._prepareRenderingGroup(renderingGroupId);
  20775. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20776. };
  20777. /**
  20778. * @param subMesh The submesh to dispatch
  20779. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20780. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20781. */
  20782. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20783. if (mesh === undefined) {
  20784. mesh = subMesh.getMesh();
  20785. }
  20786. var renderingGroupId = mesh.renderingGroupId || 0;
  20787. this._prepareRenderingGroup(renderingGroupId);
  20788. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20789. };
  20790. /**
  20791. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20792. * This allowed control for front to back rendering or reversly depending of the special needs.
  20793. *
  20794. * @param renderingGroupId The rendering group id corresponding to its index
  20795. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20796. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20797. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20798. */
  20799. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20800. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20801. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20802. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20803. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20804. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20805. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20806. if (this._renderingGroups[renderingGroupId]) {
  20807. var group = this._renderingGroups[renderingGroupId];
  20808. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20809. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20810. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20811. }
  20812. };
  20813. /**
  20814. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20815. *
  20816. * @param renderingGroupId The rendering group id corresponding to its index
  20817. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20818. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20819. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20820. */
  20821. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20822. if (depth === void 0) { depth = true; }
  20823. if (stencil === void 0) { stencil = true; }
  20824. this._autoClearDepthStencil[renderingGroupId] = {
  20825. autoClear: autoClearDepthStencil,
  20826. depth: depth,
  20827. stencil: stencil
  20828. };
  20829. };
  20830. /**
  20831. * The max id used for rendering groups (not included)
  20832. */
  20833. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20834. /**
  20835. * The min id used for rendering groups (included)
  20836. */
  20837. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20838. /**
  20839. * Used to globally prevent autoclearing scenes.
  20840. */
  20841. RenderingManager.AUTOCLEAR = true;
  20842. return RenderingManager;
  20843. }());
  20844. BABYLON.RenderingManager = RenderingManager;
  20845. })(BABYLON || (BABYLON = {}));
  20846. //# sourceMappingURL=babylon.renderingManager.js.map
  20847. var BABYLON;
  20848. (function (BABYLON) {
  20849. var RenderingGroup = /** @class */ (function () {
  20850. /**
  20851. * Creates a new rendering group.
  20852. * @param index The rendering group index
  20853. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20854. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20855. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20856. */
  20857. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20858. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20859. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20860. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20861. this.index = index;
  20862. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20863. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20864. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20865. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20866. this._particleSystems = new BABYLON.SmartArray(256);
  20867. this._spriteManagers = new BABYLON.SmartArray(256);
  20868. this._edgesRenderers = new BABYLON.SmartArray(16);
  20869. this._scene = scene;
  20870. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20871. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20872. this.transparentSortCompareFn = transparentSortCompareFn;
  20873. }
  20874. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20875. /**
  20876. * Set the opaque sort comparison function.
  20877. * If null the sub meshes will be render in the order they were created
  20878. */
  20879. set: function (value) {
  20880. this._opaqueSortCompareFn = value;
  20881. if (value) {
  20882. this._renderOpaque = this.renderOpaqueSorted;
  20883. }
  20884. else {
  20885. this._renderOpaque = RenderingGroup.renderUnsorted;
  20886. }
  20887. },
  20888. enumerable: true,
  20889. configurable: true
  20890. });
  20891. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20892. /**
  20893. * Set the alpha test sort comparison function.
  20894. * If null the sub meshes will be render in the order they were created
  20895. */
  20896. set: function (value) {
  20897. this._alphaTestSortCompareFn = value;
  20898. if (value) {
  20899. this._renderAlphaTest = this.renderAlphaTestSorted;
  20900. }
  20901. else {
  20902. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20903. }
  20904. },
  20905. enumerable: true,
  20906. configurable: true
  20907. });
  20908. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20909. /**
  20910. * Set the transparent sort comparison function.
  20911. * If null the sub meshes will be render in the order they were created
  20912. */
  20913. set: function (value) {
  20914. if (value) {
  20915. this._transparentSortCompareFn = value;
  20916. }
  20917. else {
  20918. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20919. }
  20920. this._renderTransparent = this.renderTransparentSorted;
  20921. },
  20922. enumerable: true,
  20923. configurable: true
  20924. });
  20925. /**
  20926. * Render all the sub meshes contained in the group.
  20927. * @param customRenderFunction Used to override the default render behaviour of the group.
  20928. * @returns true if rendered some submeshes.
  20929. */
  20930. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20931. if (customRenderFunction) {
  20932. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20933. return;
  20934. }
  20935. var engine = this._scene.getEngine();
  20936. // Depth only
  20937. if (this._depthOnlySubMeshes.length !== 0) {
  20938. engine.setColorWrite(false);
  20939. this._renderAlphaTest(this._depthOnlySubMeshes);
  20940. engine.setColorWrite(true);
  20941. }
  20942. // Opaque
  20943. if (this._opaqueSubMeshes.length !== 0) {
  20944. this._renderOpaque(this._opaqueSubMeshes);
  20945. }
  20946. // Alpha test
  20947. if (this._alphaTestSubMeshes.length !== 0) {
  20948. this._renderAlphaTest(this._alphaTestSubMeshes);
  20949. }
  20950. var stencilState = engine.getStencilBuffer();
  20951. engine.setStencilBuffer(false);
  20952. // Sprites
  20953. if (renderSprites) {
  20954. this._renderSprites();
  20955. }
  20956. // Particles
  20957. if (renderParticles) {
  20958. this._renderParticles(activeMeshes);
  20959. }
  20960. if (this.onBeforeTransparentRendering) {
  20961. this.onBeforeTransparentRendering();
  20962. }
  20963. // Transparent
  20964. if (this._transparentSubMeshes.length !== 0) {
  20965. this._renderTransparent(this._transparentSubMeshes);
  20966. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20967. }
  20968. // Set back stencil to false in case it changes before the edge renderer.
  20969. engine.setStencilBuffer(false);
  20970. // Edges
  20971. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20972. this._edgesRenderers.data[edgesRendererIndex].render();
  20973. }
  20974. // Restore Stencil state.
  20975. engine.setStencilBuffer(stencilState);
  20976. };
  20977. /**
  20978. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20979. * @param subMeshes The submeshes to render
  20980. */
  20981. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20982. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20983. };
  20984. /**
  20985. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20986. * @param subMeshes The submeshes to render
  20987. */
  20988. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20989. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20990. };
  20991. /**
  20992. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20993. * @param subMeshes The submeshes to render
  20994. */
  20995. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20996. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20997. };
  20998. /**
  20999. * Renders the submeshes in a specified order.
  21000. * @param subMeshes The submeshes to sort before render
  21001. * @param sortCompareFn The comparison function use to sort
  21002. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21003. * @param transparent Specifies to activate blending if true
  21004. */
  21005. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21006. var subIndex = 0;
  21007. var subMesh;
  21008. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21009. for (; subIndex < subMeshes.length; subIndex++) {
  21010. subMesh = subMeshes.data[subIndex];
  21011. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21012. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21013. }
  21014. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21015. if (sortCompareFn) {
  21016. sortedArray.sort(sortCompareFn);
  21017. }
  21018. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21019. subMesh = sortedArray[subIndex];
  21020. if (transparent) {
  21021. var material = subMesh.getMaterial();
  21022. if (material && material.needDepthPrePass) {
  21023. var engine = material.getScene().getEngine();
  21024. engine.setColorWrite(false);
  21025. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21026. subMesh.render(false);
  21027. engine.setColorWrite(true);
  21028. }
  21029. }
  21030. subMesh.render(transparent);
  21031. }
  21032. };
  21033. /**
  21034. * Renders the submeshes in the order they were dispatched (no sort applied).
  21035. * @param subMeshes The submeshes to render
  21036. */
  21037. RenderingGroup.renderUnsorted = function (subMeshes) {
  21038. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21039. var submesh = subMeshes.data[subIndex];
  21040. submesh.render(false);
  21041. }
  21042. };
  21043. /**
  21044. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21045. * are rendered back to front if in the same alpha index.
  21046. *
  21047. * @param a The first submesh
  21048. * @param b The second submesh
  21049. * @returns The result of the comparison
  21050. */
  21051. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21052. // Alpha index first
  21053. if (a._alphaIndex > b._alphaIndex) {
  21054. return 1;
  21055. }
  21056. if (a._alphaIndex < b._alphaIndex) {
  21057. return -1;
  21058. }
  21059. // Then distance to camera
  21060. return RenderingGroup.backToFrontSortCompare(a, b);
  21061. };
  21062. /**
  21063. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21064. * are rendered back to front.
  21065. *
  21066. * @param a The first submesh
  21067. * @param b The second submesh
  21068. * @returns The result of the comparison
  21069. */
  21070. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21071. // Then distance to camera
  21072. if (a._distanceToCamera < b._distanceToCamera) {
  21073. return 1;
  21074. }
  21075. if (a._distanceToCamera > b._distanceToCamera) {
  21076. return -1;
  21077. }
  21078. return 0;
  21079. };
  21080. /**
  21081. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21082. * are rendered front to back (prevent overdraw).
  21083. *
  21084. * @param a The first submesh
  21085. * @param b The second submesh
  21086. * @returns The result of the comparison
  21087. */
  21088. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21089. // Then distance to camera
  21090. if (a._distanceToCamera < b._distanceToCamera) {
  21091. return -1;
  21092. }
  21093. if (a._distanceToCamera > b._distanceToCamera) {
  21094. return 1;
  21095. }
  21096. return 0;
  21097. };
  21098. /**
  21099. * Resets the different lists of submeshes to prepare a new frame.
  21100. */
  21101. RenderingGroup.prototype.prepare = function () {
  21102. this._opaqueSubMeshes.reset();
  21103. this._transparentSubMeshes.reset();
  21104. this._alphaTestSubMeshes.reset();
  21105. this._depthOnlySubMeshes.reset();
  21106. this._particleSystems.reset();
  21107. this._spriteManagers.reset();
  21108. this._edgesRenderers.reset();
  21109. };
  21110. RenderingGroup.prototype.dispose = function () {
  21111. this._opaqueSubMeshes.dispose();
  21112. this._transparentSubMeshes.dispose();
  21113. this._alphaTestSubMeshes.dispose();
  21114. this._depthOnlySubMeshes.dispose();
  21115. this._particleSystems.dispose();
  21116. this._spriteManagers.dispose();
  21117. this._edgesRenderers.dispose();
  21118. };
  21119. /**
  21120. * Inserts the submesh in its correct queue depending on its material.
  21121. * @param subMesh The submesh to dispatch
  21122. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21123. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21124. */
  21125. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21126. // Get mesh and materials if not provided
  21127. if (mesh === undefined) {
  21128. mesh = subMesh.getMesh();
  21129. }
  21130. if (material === undefined) {
  21131. material = subMesh.getMaterial();
  21132. }
  21133. if (material === null || material === undefined) {
  21134. return;
  21135. }
  21136. if (material.needAlphaBlendingForMesh(mesh)) {
  21137. this._transparentSubMeshes.push(subMesh);
  21138. }
  21139. else if (material.needAlphaTesting()) {
  21140. if (material.needDepthPrePass) {
  21141. this._depthOnlySubMeshes.push(subMesh);
  21142. }
  21143. this._alphaTestSubMeshes.push(subMesh);
  21144. }
  21145. else {
  21146. if (material.needDepthPrePass) {
  21147. this._depthOnlySubMeshes.push(subMesh);
  21148. }
  21149. this._opaqueSubMeshes.push(subMesh); // Opaque
  21150. }
  21151. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21152. this._edgesRenderers.push(mesh._edgesRenderer);
  21153. }
  21154. };
  21155. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21156. this._spriteManagers.push(spriteManager);
  21157. };
  21158. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21159. this._particleSystems.push(particleSystem);
  21160. };
  21161. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21162. if (this._particleSystems.length === 0) {
  21163. return;
  21164. }
  21165. // Particles
  21166. var activeCamera = this._scene.activeCamera;
  21167. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21168. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21169. var particleSystem = this._particleSystems.data[particleIndex];
  21170. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21171. continue;
  21172. }
  21173. var emitter = particleSystem.emitter;
  21174. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21175. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21176. }
  21177. }
  21178. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21179. };
  21180. RenderingGroup.prototype._renderSprites = function () {
  21181. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21182. return;
  21183. }
  21184. // Sprites
  21185. var activeCamera = this._scene.activeCamera;
  21186. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21187. for (var id = 0; id < this._spriteManagers.length; id++) {
  21188. var spriteManager = this._spriteManagers.data[id];
  21189. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21190. spriteManager.render();
  21191. }
  21192. }
  21193. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21194. };
  21195. return RenderingGroup;
  21196. }());
  21197. BABYLON.RenderingGroup = RenderingGroup;
  21198. })(BABYLON || (BABYLON = {}));
  21199. //# sourceMappingURL=babylon.renderingGroup.js.map
  21200. var BABYLON;
  21201. (function (BABYLON) {
  21202. var ClickInfo = /** @class */ (function () {
  21203. function ClickInfo() {
  21204. this._singleClick = false;
  21205. this._doubleClick = false;
  21206. this._hasSwiped = false;
  21207. this._ignore = false;
  21208. }
  21209. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21210. get: function () {
  21211. return this._singleClick;
  21212. },
  21213. set: function (b) {
  21214. this._singleClick = b;
  21215. },
  21216. enumerable: true,
  21217. configurable: true
  21218. });
  21219. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21220. get: function () {
  21221. return this._doubleClick;
  21222. },
  21223. set: function (b) {
  21224. this._doubleClick = b;
  21225. },
  21226. enumerable: true,
  21227. configurable: true
  21228. });
  21229. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21230. get: function () {
  21231. return this._hasSwiped;
  21232. },
  21233. set: function (b) {
  21234. this._hasSwiped = b;
  21235. },
  21236. enumerable: true,
  21237. configurable: true
  21238. });
  21239. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21240. get: function () {
  21241. return this._ignore;
  21242. },
  21243. set: function (b) {
  21244. this._ignore = b;
  21245. },
  21246. enumerable: true,
  21247. configurable: true
  21248. });
  21249. return ClickInfo;
  21250. }());
  21251. /**
  21252. * This class is used by the onRenderingGroupObservable
  21253. */
  21254. var RenderingGroupInfo = /** @class */ (function () {
  21255. function RenderingGroupInfo() {
  21256. }
  21257. /**
  21258. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21259. * This stage will be fired no matter what
  21260. */
  21261. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21262. /**
  21263. * Called before opaque object are rendered.
  21264. * This stage will be fired only if there's 3D Opaque content to render
  21265. */
  21266. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21267. /**
  21268. * Called after the opaque objects are rendered and before the transparent ones
  21269. * This stage will be fired only if there's 3D transparent content to render
  21270. */
  21271. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21272. /**
  21273. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21274. * This stage will be fired no matter what
  21275. */
  21276. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21277. return RenderingGroupInfo;
  21278. }());
  21279. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21280. /**
  21281. * Represents a scene to be rendered by the engine.
  21282. * @see http://doc.babylonjs.com/page.php?p=21911
  21283. */
  21284. var Scene = /** @class */ (function () {
  21285. /**
  21286. * @constructor
  21287. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21288. */
  21289. function Scene(engine) {
  21290. // Members
  21291. this.autoClear = true;
  21292. this.autoClearDepthAndStencil = true;
  21293. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21294. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21295. this.forceWireframe = false;
  21296. this._forcePointsCloud = false;
  21297. this.forceShowBoundingBoxes = false;
  21298. this.animationsEnabled = true;
  21299. this.useConstantAnimationDeltaTime = false;
  21300. this.constantlyUpdateMeshUnderPointer = false;
  21301. this.hoverCursor = "pointer";
  21302. this.defaultCursor = "";
  21303. /**
  21304. * This is used to call preventDefault() on pointer down
  21305. * in order to block unwanted artifacts like system double clicks
  21306. */
  21307. this.preventDefaultOnPointerDown = true;
  21308. // Metadata
  21309. this.metadata = null;
  21310. /**
  21311. * An event triggered when the scene is disposed.
  21312. * @type {BABYLON.Observable}
  21313. */
  21314. this.onDisposeObservable = new BABYLON.Observable();
  21315. /**
  21316. * An event triggered before rendering the scene (right after animations and physics)
  21317. * @type {BABYLON.Observable}
  21318. */
  21319. this.onBeforeRenderObservable = new BABYLON.Observable();
  21320. /**
  21321. * An event triggered after rendering the scene
  21322. * @type {BABYLON.Observable}
  21323. */
  21324. this.onAfterRenderObservable = new BABYLON.Observable();
  21325. /**
  21326. * An event triggered before animating the scene
  21327. * @type {BABYLON.Observable}
  21328. */
  21329. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21330. /**
  21331. * An event triggered after animations processing
  21332. * @type {BABYLON.Observable}
  21333. */
  21334. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21335. /**
  21336. * An event triggered before draw calls are ready to be sent
  21337. * @type {BABYLON.Observable}
  21338. */
  21339. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21340. /**
  21341. * An event triggered after draw calls have been sent
  21342. * @type {BABYLON.Observable}
  21343. */
  21344. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21345. /**
  21346. * An event triggered when physic simulation is about to be run
  21347. * @type {BABYLON.Observable}
  21348. */
  21349. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21350. /**
  21351. * An event triggered when physic simulation has been done
  21352. * @type {BABYLON.Observable}
  21353. */
  21354. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21355. /**
  21356. * An event triggered when the scene is ready
  21357. * @type {BABYLON.Observable}
  21358. */
  21359. this.onReadyObservable = new BABYLON.Observable();
  21360. /**
  21361. * An event triggered before rendering a camera
  21362. * @type {BABYLON.Observable}
  21363. */
  21364. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21365. /**
  21366. * An event triggered after rendering a camera
  21367. * @type {BABYLON.Observable}
  21368. */
  21369. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21370. /**
  21371. * An event triggered when active meshes evaluation is about to start
  21372. * @type {BABYLON.Observable}
  21373. */
  21374. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21375. /**
  21376. * An event triggered when active meshes evaluation is done
  21377. * @type {BABYLON.Observable}
  21378. */
  21379. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21380. /**
  21381. * An event triggered when particles rendering is about to start
  21382. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21383. * @type {BABYLON.Observable}
  21384. */
  21385. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21386. /**
  21387. * An event triggered when particles rendering is done
  21388. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21389. * @type {BABYLON.Observable}
  21390. */
  21391. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21392. /**
  21393. * An event triggered when sprites rendering is about to start
  21394. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21395. * @type {BABYLON.Observable}
  21396. */
  21397. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21398. /**
  21399. * An event triggered when sprites rendering is done
  21400. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21401. * @type {BABYLON.Observable}
  21402. */
  21403. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21404. /**
  21405. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21406. * @type {BABYLON.Observable}
  21407. */
  21408. this.onDataLoadedObservable = new BABYLON.Observable();
  21409. /**
  21410. * An event triggered when a camera is created
  21411. * @type {BABYLON.Observable}
  21412. */
  21413. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21414. /**
  21415. * An event triggered when a camera is removed
  21416. * @type {BABYLON.Observable}
  21417. */
  21418. this.onCameraRemovedObservable = new BABYLON.Observable();
  21419. /**
  21420. * An event triggered when a light is created
  21421. * @type {BABYLON.Observable}
  21422. */
  21423. this.onNewLightAddedObservable = new BABYLON.Observable();
  21424. /**
  21425. * An event triggered when a light is removed
  21426. * @type {BABYLON.Observable}
  21427. */
  21428. this.onLightRemovedObservable = new BABYLON.Observable();
  21429. /**
  21430. * An event triggered when a geometry is created
  21431. * @type {BABYLON.Observable}
  21432. */
  21433. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21434. /**
  21435. * An event triggered when a geometry is removed
  21436. * @type {BABYLON.Observable}
  21437. */
  21438. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21439. /**
  21440. * An event triggered when a transform node is created
  21441. * @type {BABYLON.Observable}
  21442. */
  21443. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21444. /**
  21445. * An event triggered when a transform node is removed
  21446. * @type {BABYLON.Observable}
  21447. */
  21448. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21449. /**
  21450. * An event triggered when a mesh is created
  21451. * @type {BABYLON.Observable}
  21452. */
  21453. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21454. /**
  21455. * An event triggered when a mesh is removed
  21456. * @type {BABYLON.Observable}
  21457. */
  21458. this.onMeshRemovedObservable = new BABYLON.Observable();
  21459. /**
  21460. * An event triggered when render targets are about to be rendered
  21461. * Can happen multiple times per frame.
  21462. * @type {BABYLON.Observable}
  21463. */
  21464. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21465. /**
  21466. * An event triggered when render targets were rendered.
  21467. * Can happen multiple times per frame.
  21468. * @type {BABYLON.Observable}
  21469. */
  21470. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21471. /**
  21472. * An event triggered before calculating deterministic simulation step
  21473. * @type {BABYLON.Observable}
  21474. */
  21475. this.onBeforeStepObservable = new BABYLON.Observable();
  21476. /**
  21477. * An event triggered after calculating deterministic simulation step
  21478. * @type {BABYLON.Observable}
  21479. */
  21480. this.onAfterStepObservable = new BABYLON.Observable();
  21481. /**
  21482. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21483. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21484. * 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)
  21485. */
  21486. this.onRenderingGroupObservable = new BABYLON.Observable();
  21487. // Animations
  21488. this.animations = [];
  21489. /**
  21490. * 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).
  21491. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21492. */
  21493. this.onPrePointerObservable = new BABYLON.Observable();
  21494. /**
  21495. * Observable event triggered each time an input event is received from the rendering canvas
  21496. */
  21497. this.onPointerObservable = new BABYLON.Observable();
  21498. this._meshPickProceed = false;
  21499. this._currentPickResult = null;
  21500. this._previousPickResult = null;
  21501. this._totalPointersPressed = 0;
  21502. this._doubleClickOccured = false;
  21503. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21504. this.cameraToUseForPointers = null;
  21505. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21506. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21507. this._startingPointerTime = 0;
  21508. this._previousStartingPointerTime = 0;
  21509. // Deterministic lockstep
  21510. this._timeAccumulator = 0;
  21511. this._currentStepId = 0;
  21512. this._currentInternalStep = 0;
  21513. // Keyboard
  21514. /**
  21515. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21516. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21517. */
  21518. this.onPreKeyboardObservable = new BABYLON.Observable();
  21519. /**
  21520. * Observable event triggered each time an keyboard event is received from the hosting window
  21521. */
  21522. this.onKeyboardObservable = new BABYLON.Observable();
  21523. // Coordinate system
  21524. /**
  21525. * use right-handed coordinate system on this scene.
  21526. * @type {boolean}
  21527. */
  21528. this._useRightHandedSystem = false;
  21529. // Fog
  21530. this._fogEnabled = true;
  21531. this._fogMode = Scene.FOGMODE_NONE;
  21532. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21533. this.fogDensity = 0.1;
  21534. this.fogStart = 0;
  21535. this.fogEnd = 1000.0;
  21536. // Lights
  21537. /**
  21538. * is shadow enabled on this scene.
  21539. * @type {boolean}
  21540. */
  21541. this._shadowsEnabled = true;
  21542. /**
  21543. * is light enabled on this scene.
  21544. * @type {boolean}
  21545. */
  21546. this._lightsEnabled = true;
  21547. /**
  21548. * All of the lights added to this scene.
  21549. * @see BABYLON.Light
  21550. * @type {BABYLON.Light[]}
  21551. */
  21552. this.lights = new Array();
  21553. // Cameras
  21554. /** All of the cameras added to this scene. */
  21555. this.cameras = new Array();
  21556. /** All of the active cameras added to this scene. */
  21557. this.activeCameras = new Array();
  21558. // Meshes
  21559. /**
  21560. * All of the tranform nodes added to this scene.
  21561. * @see BABYLON.TransformNode
  21562. * @type {BABYLON.TransformNode[]}
  21563. */
  21564. this.transformNodes = new Array();
  21565. /**
  21566. * All of the (abstract) meshes added to this scene.
  21567. * @see BABYLON.AbstractMesh
  21568. * @type {BABYLON.AbstractMesh[]}
  21569. */
  21570. this.meshes = new Array();
  21571. /**
  21572. * All of the animation groups added to this scene.
  21573. * @see BABYLON.AnimationGroup
  21574. * @type {BABYLON.AnimationGroup[]}
  21575. */
  21576. this.animationGroups = new Array();
  21577. // Geometries
  21578. this._geometries = new Array();
  21579. this.materials = new Array();
  21580. this.multiMaterials = new Array();
  21581. // Textures
  21582. this._texturesEnabled = true;
  21583. this.textures = new Array();
  21584. // Particles
  21585. this.particlesEnabled = true;
  21586. this.particleSystems = new Array();
  21587. // Sprites
  21588. this.spritesEnabled = true;
  21589. this.spriteManagers = new Array();
  21590. /**
  21591. * The list of layers (background and foreground) of the scene.
  21592. */
  21593. this.layers = new Array();
  21594. /**
  21595. * The list of effect layers (highlights/glow) contained in the scene.
  21596. */
  21597. this.effectLayers = new Array();
  21598. // Skeletons
  21599. this._skeletonsEnabled = true;
  21600. this.skeletons = new Array();
  21601. // Morph targets
  21602. this.morphTargetManagers = new Array();
  21603. // Lens flares
  21604. this.lensFlaresEnabled = true;
  21605. this.lensFlareSystems = new Array();
  21606. // Collisions
  21607. this.collisionsEnabled = true;
  21608. /** Defines the gravity applied to this scene */
  21609. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21610. // Postprocesses
  21611. this.postProcesses = new Array();
  21612. this.postProcessesEnabled = true;
  21613. // Customs render targets
  21614. this.renderTargetsEnabled = true;
  21615. this.dumpNextRenderTargets = false;
  21616. this.customRenderTargets = new Array();
  21617. // Imported meshes
  21618. this.importedMeshesFiles = new Array();
  21619. // Probes
  21620. this.probesEnabled = true;
  21621. this.reflectionProbes = new Array();
  21622. this._actionManagers = new Array();
  21623. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21624. // Procedural textures
  21625. this.proceduralTexturesEnabled = true;
  21626. this._proceduralTextures = new Array();
  21627. this.soundTracks = new Array();
  21628. this._audioEnabled = true;
  21629. this._headphone = false;
  21630. // Performance counters
  21631. this._totalVertices = new BABYLON.PerfCounter();
  21632. this._activeIndices = new BABYLON.PerfCounter();
  21633. this._activeParticles = new BABYLON.PerfCounter();
  21634. this._activeBones = new BABYLON.PerfCounter();
  21635. this._animationTime = 0;
  21636. this.animationTimeScale = 1;
  21637. this._renderId = 0;
  21638. this._executeWhenReadyTimeoutId = -1;
  21639. this._intermediateRendering = false;
  21640. this._viewUpdateFlag = -1;
  21641. this._projectionUpdateFlag = -1;
  21642. this._alternateViewUpdateFlag = -1;
  21643. this._alternateProjectionUpdateFlag = -1;
  21644. this._toBeDisposed = new BABYLON.SmartArray(256);
  21645. this._activeRequests = new Array();
  21646. this._pendingData = new Array();
  21647. this._isDisposed = false;
  21648. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21649. this._activeMeshes = new BABYLON.SmartArray(256);
  21650. this._processedMaterials = new BABYLON.SmartArray(256);
  21651. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21652. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21653. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21654. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21655. this._activeAnimatables = new Array();
  21656. this._transformMatrix = BABYLON.Matrix.Zero();
  21657. this._useAlternateCameraConfiguration = false;
  21658. this._alternateRendering = false;
  21659. this.requireLightSorting = false;
  21660. this._depthRenderer = {};
  21661. this._activeMeshesFrozen = false;
  21662. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21663. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21664. this._engine.scenes.push(this);
  21665. this._uid = null;
  21666. this._renderingManager = new BABYLON.RenderingManager(this);
  21667. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21668. if (BABYLON.OutlineRenderer) {
  21669. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21670. }
  21671. if (BABYLON.Tools.IsWindowObjectExist()) {
  21672. this.attachControl();
  21673. }
  21674. //simplification queue
  21675. if (BABYLON.SimplificationQueue) {
  21676. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21677. }
  21678. //collision coordinator initialization. For now legacy per default.
  21679. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21680. // Uniform Buffer
  21681. this._createUbo();
  21682. // Default Image processing definition.
  21683. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21684. }
  21685. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21686. /** The fog is deactivated */
  21687. get: function () {
  21688. return Scene._FOGMODE_NONE;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21694. /** The fog density is following an exponential function */
  21695. get: function () {
  21696. return Scene._FOGMODE_EXP;
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21702. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21703. get: function () {
  21704. return Scene._FOGMODE_EXP2;
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21710. /** The fog density is following a linear function. */
  21711. get: function () {
  21712. return Scene._FOGMODE_LINEAR;
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21718. /**
  21719. * Texture used in all pbr material as the reflection texture.
  21720. * As in the majority of the scene they are the same (exception for multi room and so on),
  21721. * this is easier to reference from here than from all the materials.
  21722. */
  21723. get: function () {
  21724. return this._environmentTexture;
  21725. },
  21726. /**
  21727. * Texture used in all pbr material as the reflection texture.
  21728. * As in the majority of the scene they are the same (exception for multi room and so on),
  21729. * this is easier to set here than in all the materials.
  21730. */
  21731. set: function (value) {
  21732. if (this._environmentTexture === value) {
  21733. return;
  21734. }
  21735. this._environmentTexture = value;
  21736. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21742. /**
  21743. * Default image processing configuration used either in the rendering
  21744. * Forward main pass or through the imageProcessingPostProcess if present.
  21745. * As in the majority of the scene they are the same (exception for multi camera),
  21746. * this is easier to reference from here than from all the materials and post process.
  21747. *
  21748. * No setter as we it is a shared configuration, you can set the values instead.
  21749. */
  21750. get: function () {
  21751. return this._imageProcessingConfiguration;
  21752. },
  21753. enumerable: true,
  21754. configurable: true
  21755. });
  21756. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21757. get: function () {
  21758. return this._forcePointsCloud;
  21759. },
  21760. set: function (value) {
  21761. if (this._forcePointsCloud === value) {
  21762. return;
  21763. }
  21764. this._forcePointsCloud = value;
  21765. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21766. },
  21767. enumerable: true,
  21768. configurable: true
  21769. });
  21770. Object.defineProperty(Scene.prototype, "onDispose", {
  21771. /** A function to be executed when this scene is disposed. */
  21772. set: function (callback) {
  21773. if (this._onDisposeObserver) {
  21774. this.onDisposeObservable.remove(this._onDisposeObserver);
  21775. }
  21776. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21777. },
  21778. enumerable: true,
  21779. configurable: true
  21780. });
  21781. Object.defineProperty(Scene.prototype, "beforeRender", {
  21782. /** A function to be executed before rendering this scene */
  21783. set: function (callback) {
  21784. if (this._onBeforeRenderObserver) {
  21785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21786. }
  21787. if (callback) {
  21788. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21789. }
  21790. },
  21791. enumerable: true,
  21792. configurable: true
  21793. });
  21794. Object.defineProperty(Scene.prototype, "afterRender", {
  21795. /** A function to be executed after rendering this scene */
  21796. set: function (callback) {
  21797. if (this._onAfterRenderObserver) {
  21798. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21799. }
  21800. if (callback) {
  21801. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21802. }
  21803. },
  21804. enumerable: true,
  21805. configurable: true
  21806. });
  21807. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21808. set: function (callback) {
  21809. if (this._onBeforeCameraRenderObserver) {
  21810. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21811. }
  21812. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21818. set: function (callback) {
  21819. if (this._onAfterCameraRenderObserver) {
  21820. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21821. }
  21822. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21823. },
  21824. enumerable: true,
  21825. configurable: true
  21826. });
  21827. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21828. get: function () {
  21829. if (!this._gamepadManager) {
  21830. this._gamepadManager = new BABYLON.GamepadManager(this);
  21831. }
  21832. return this._gamepadManager;
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21838. get: function () {
  21839. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21845. get: function () {
  21846. return this._useRightHandedSystem;
  21847. },
  21848. set: function (value) {
  21849. if (this._useRightHandedSystem === value) {
  21850. return;
  21851. }
  21852. this._useRightHandedSystem = value;
  21853. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Scene.prototype.setStepId = function (newStepId) {
  21859. this._currentStepId = newStepId;
  21860. };
  21861. ;
  21862. Scene.prototype.getStepId = function () {
  21863. return this._currentStepId;
  21864. };
  21865. ;
  21866. Scene.prototype.getInternalStep = function () {
  21867. return this._currentInternalStep;
  21868. };
  21869. ;
  21870. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21871. get: function () {
  21872. return this._fogEnabled;
  21873. },
  21874. /**
  21875. * is fog enabled on this scene.
  21876. */
  21877. set: function (value) {
  21878. if (this._fogEnabled === value) {
  21879. return;
  21880. }
  21881. this._fogEnabled = value;
  21882. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(Scene.prototype, "fogMode", {
  21888. get: function () {
  21889. return this._fogMode;
  21890. },
  21891. set: function (value) {
  21892. if (this._fogMode === value) {
  21893. return;
  21894. }
  21895. this._fogMode = value;
  21896. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21902. get: function () {
  21903. return this._shadowsEnabled;
  21904. },
  21905. set: function (value) {
  21906. if (this._shadowsEnabled === value) {
  21907. return;
  21908. }
  21909. this._shadowsEnabled = value;
  21910. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21911. },
  21912. enumerable: true,
  21913. configurable: true
  21914. });
  21915. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21916. get: function () {
  21917. return this._lightsEnabled;
  21918. },
  21919. set: function (value) {
  21920. if (this._lightsEnabled === value) {
  21921. return;
  21922. }
  21923. this._lightsEnabled = value;
  21924. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21925. },
  21926. enumerable: true,
  21927. configurable: true
  21928. });
  21929. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21930. /** The default material used on meshes when no material is affected */
  21931. get: function () {
  21932. if (!this._defaultMaterial) {
  21933. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21934. }
  21935. return this._defaultMaterial;
  21936. },
  21937. /** The default material used on meshes when no material is affected */
  21938. set: function (value) {
  21939. this._defaultMaterial = value;
  21940. },
  21941. enumerable: true,
  21942. configurable: true
  21943. });
  21944. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21945. get: function () {
  21946. return this._texturesEnabled;
  21947. },
  21948. set: function (value) {
  21949. if (this._texturesEnabled === value) {
  21950. return;
  21951. }
  21952. this._texturesEnabled = value;
  21953. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21954. },
  21955. enumerable: true,
  21956. configurable: true
  21957. });
  21958. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21959. get: function () {
  21960. return this._skeletonsEnabled;
  21961. },
  21962. set: function (value) {
  21963. if (this._skeletonsEnabled === value) {
  21964. return;
  21965. }
  21966. this._skeletonsEnabled = value;
  21967. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21973. get: function () {
  21974. if (!this._postProcessRenderPipelineManager) {
  21975. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21976. }
  21977. return this._postProcessRenderPipelineManager;
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21983. get: function () {
  21984. if (!this._mainSoundTrack) {
  21985. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21986. }
  21987. return this._mainSoundTrack;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21993. get: function () {
  21994. return this._alternateRendering;
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22000. get: function () {
  22001. return this._frustumPlanes;
  22002. },
  22003. enumerable: true,
  22004. configurable: true
  22005. });
  22006. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22007. /**
  22008. * Gets the current geometry buffer associated to the scene.
  22009. */
  22010. get: function () {
  22011. return this._geometryBufferRenderer;
  22012. },
  22013. /**
  22014. * Sets the current geometry buffer for the scene.
  22015. */
  22016. set: function (geometryBufferRenderer) {
  22017. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22018. this._geometryBufferRenderer = geometryBufferRenderer;
  22019. }
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Scene.prototype, "debugLayer", {
  22025. // Properties
  22026. get: function () {
  22027. if (!this._debugLayer) {
  22028. this._debugLayer = new BABYLON.DebugLayer(this);
  22029. }
  22030. return this._debugLayer;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22036. get: function () {
  22037. return this._workerCollisions;
  22038. },
  22039. set: function (enabled) {
  22040. if (!BABYLON.CollisionCoordinatorLegacy) {
  22041. return;
  22042. }
  22043. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22044. this._workerCollisions = enabled;
  22045. if (this.collisionCoordinator) {
  22046. this.collisionCoordinator.destroy();
  22047. }
  22048. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22049. this.collisionCoordinator.init(this);
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22055. get: function () {
  22056. return this._selectionOctree;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22062. /**
  22063. * The mesh that is currently under the pointer.
  22064. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22065. */
  22066. get: function () {
  22067. return this._pointerOverMesh;
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Object.defineProperty(Scene.prototype, "pointerX", {
  22073. /**
  22074. * Current on-screen X position of the pointer
  22075. * @return {number} X position of the pointer
  22076. */
  22077. get: function () {
  22078. return this._pointerX;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(Scene.prototype, "pointerY", {
  22084. /**
  22085. * Current on-screen Y position of the pointer
  22086. * @return {number} Y position of the pointer
  22087. */
  22088. get: function () {
  22089. return this._pointerY;
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Scene.prototype.getCachedMaterial = function () {
  22095. return this._cachedMaterial;
  22096. };
  22097. Scene.prototype.getCachedEffect = function () {
  22098. return this._cachedEffect;
  22099. };
  22100. Scene.prototype.getCachedVisibility = function () {
  22101. return this._cachedVisibility;
  22102. };
  22103. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22104. if (visibility === void 0) { visibility = 1; }
  22105. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22106. };
  22107. Scene.prototype.getBoundingBoxRenderer = function () {
  22108. if (!this._boundingBoxRenderer) {
  22109. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22110. }
  22111. return this._boundingBoxRenderer;
  22112. };
  22113. Scene.prototype.getOutlineRenderer = function () {
  22114. return this._outlineRenderer;
  22115. };
  22116. Scene.prototype.getEngine = function () {
  22117. return this._engine;
  22118. };
  22119. Scene.prototype.getTotalVertices = function () {
  22120. return this._totalVertices.current;
  22121. };
  22122. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22123. get: function () {
  22124. return this._totalVertices;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Scene.prototype.getActiveIndices = function () {
  22130. return this._activeIndices.current;
  22131. };
  22132. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22133. get: function () {
  22134. return this._activeIndices;
  22135. },
  22136. enumerable: true,
  22137. configurable: true
  22138. });
  22139. Scene.prototype.getActiveParticles = function () {
  22140. return this._activeParticles.current;
  22141. };
  22142. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22143. get: function () {
  22144. return this._activeParticles;
  22145. },
  22146. enumerable: true,
  22147. configurable: true
  22148. });
  22149. Scene.prototype.getActiveBones = function () {
  22150. return this._activeBones.current;
  22151. };
  22152. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22153. get: function () {
  22154. return this._activeBones;
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. // Stats
  22160. Scene.prototype.getInterFramePerfCounter = function () {
  22161. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22162. return 0;
  22163. };
  22164. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22165. get: function () {
  22166. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22167. return null;
  22168. },
  22169. enumerable: true,
  22170. configurable: true
  22171. });
  22172. Scene.prototype.getLastFrameDuration = function () {
  22173. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22174. return 0;
  22175. };
  22176. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22177. get: function () {
  22178. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22179. return null;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22185. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22186. return 0;
  22187. };
  22188. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22189. get: function () {
  22190. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22191. return null;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. Scene.prototype.getActiveMeshes = function () {
  22197. return this._activeMeshes;
  22198. };
  22199. Scene.prototype.getRenderTargetsDuration = function () {
  22200. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22201. return 0;
  22202. };
  22203. Scene.prototype.getRenderDuration = function () {
  22204. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22205. return 0;
  22206. };
  22207. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22208. get: function () {
  22209. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22210. return null;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Scene.prototype.getParticlesDuration = function () {
  22216. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22217. return 0;
  22218. };
  22219. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22220. get: function () {
  22221. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22222. return null;
  22223. },
  22224. enumerable: true,
  22225. configurable: true
  22226. });
  22227. Scene.prototype.getSpritesDuration = function () {
  22228. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22229. return 0;
  22230. };
  22231. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22232. get: function () {
  22233. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22234. return null;
  22235. },
  22236. enumerable: true,
  22237. configurable: true
  22238. });
  22239. Scene.prototype.getAnimationRatio = function () {
  22240. return this._animationRatio;
  22241. };
  22242. Scene.prototype.getRenderId = function () {
  22243. return this._renderId;
  22244. };
  22245. Scene.prototype.incrementRenderId = function () {
  22246. this._renderId++;
  22247. };
  22248. Scene.prototype._updatePointerPosition = function (evt) {
  22249. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22250. if (!canvasRect) {
  22251. return;
  22252. }
  22253. this._pointerX = evt.clientX - canvasRect.left;
  22254. this._pointerY = evt.clientY - canvasRect.top;
  22255. this._unTranslatedPointerX = this._pointerX;
  22256. this._unTranslatedPointerY = this._pointerY;
  22257. };
  22258. Scene.prototype._createUbo = function () {
  22259. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22260. this._sceneUbo.addUniform("viewProjection", 16);
  22261. this._sceneUbo.addUniform("view", 16);
  22262. };
  22263. Scene.prototype._createAlternateUbo = function () {
  22264. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22265. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22266. this._alternateSceneUbo.addUniform("view", 16);
  22267. };
  22268. // Pointers handling
  22269. /**
  22270. * Use this method to simulate a pointer move on a mesh
  22271. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22272. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22273. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22274. */
  22275. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22276. var evt = new PointerEvent("pointermove", pointerEventInit);
  22277. return this._processPointerMove(pickResult, evt);
  22278. };
  22279. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22280. var canvas = this._engine.getRenderingCanvas();
  22281. if (!canvas) {
  22282. return this;
  22283. }
  22284. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22285. this.setPointerOverSprite(null);
  22286. this.setPointerOverMesh(pickResult.pickedMesh);
  22287. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22288. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22289. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22290. }
  22291. else {
  22292. canvas.style.cursor = this.hoverCursor;
  22293. }
  22294. }
  22295. else {
  22296. canvas.style.cursor = this.defaultCursor;
  22297. }
  22298. }
  22299. else {
  22300. this.setPointerOverMesh(null);
  22301. // Sprites
  22302. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22303. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22304. this.setPointerOverSprite(pickResult.pickedSprite);
  22305. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22306. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22307. }
  22308. else {
  22309. canvas.style.cursor = this.hoverCursor;
  22310. }
  22311. }
  22312. else {
  22313. this.setPointerOverSprite(null);
  22314. // Restore pointer
  22315. canvas.style.cursor = this.defaultCursor;
  22316. }
  22317. }
  22318. if (pickResult) {
  22319. if (this.onPointerMove) {
  22320. this.onPointerMove(evt, pickResult);
  22321. }
  22322. if (this.onPointerObservable.hasObservers()) {
  22323. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22324. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22325. this.onPointerObservable.notifyObservers(pi, type);
  22326. }
  22327. }
  22328. return this;
  22329. };
  22330. /**
  22331. * Use this method to simulate a pointer down on a mesh
  22332. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22333. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22334. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22335. */
  22336. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22337. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22338. return this._processPointerDown(pickResult, evt);
  22339. };
  22340. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22341. var _this = this;
  22342. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22343. this._pickedDownMesh = pickResult.pickedMesh;
  22344. var actionManager = pickResult.pickedMesh.actionManager;
  22345. if (actionManager) {
  22346. if (actionManager.hasPickTriggers) {
  22347. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22348. switch (evt.button) {
  22349. case 0:
  22350. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22351. break;
  22352. case 1:
  22353. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22354. break;
  22355. case 2:
  22356. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22357. break;
  22358. }
  22359. }
  22360. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22361. window.setTimeout(function () {
  22362. 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);
  22363. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22364. if (_this._totalPointersPressed !== 0 &&
  22365. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22366. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22367. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22368. _this._startingPointerTime = 0;
  22369. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22370. }
  22371. }
  22372. }, Scene.LongPressDelay);
  22373. }
  22374. }
  22375. }
  22376. if (pickResult) {
  22377. if (this.onPointerDown) {
  22378. this.onPointerDown(evt, pickResult);
  22379. }
  22380. if (this.onPointerObservable.hasObservers()) {
  22381. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22383. this.onPointerObservable.notifyObservers(pi, type);
  22384. }
  22385. }
  22386. return this;
  22387. };
  22388. /**
  22389. * Use this method to simulate a pointer up on a mesh
  22390. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22391. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22392. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22393. */
  22394. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22395. var evt = new PointerEvent("pointerup", pointerEventInit);
  22396. var clickInfo = new ClickInfo();
  22397. clickInfo.singleClick = true;
  22398. clickInfo.ignore = true;
  22399. return this._processPointerUp(pickResult, evt, clickInfo);
  22400. };
  22401. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22402. if (pickResult && pickResult && pickResult.pickedMesh) {
  22403. this._pickedUpMesh = pickResult.pickedMesh;
  22404. if (this._pickedDownMesh === this._pickedUpMesh) {
  22405. if (this.onPointerPick) {
  22406. this.onPointerPick(evt, pickResult);
  22407. }
  22408. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22409. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22410. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22411. this.onPointerObservable.notifyObservers(pi, type);
  22412. }
  22413. }
  22414. if (pickResult.pickedMesh.actionManager) {
  22415. if (clickInfo.ignore) {
  22416. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22417. }
  22418. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22419. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22420. }
  22421. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22422. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22423. }
  22424. }
  22425. }
  22426. if (this._pickedDownMesh &&
  22427. this._pickedDownMesh.actionManager &&
  22428. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22429. this._pickedDownMesh !== this._pickedUpMesh) {
  22430. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22431. }
  22432. if (this.onPointerUp) {
  22433. this.onPointerUp(evt, pickResult);
  22434. }
  22435. if (this.onPointerObservable.hasObservers()) {
  22436. if (!clickInfo.ignore) {
  22437. if (!clickInfo.hasSwiped) {
  22438. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22439. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22440. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22441. this.onPointerObservable.notifyObservers(pi, type);
  22442. }
  22443. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22444. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22445. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22446. this.onPointerObservable.notifyObservers(pi, type);
  22447. }
  22448. }
  22449. }
  22450. else {
  22451. var type = BABYLON.PointerEventTypes.POINTERUP;
  22452. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22453. this.onPointerObservable.notifyObservers(pi, type);
  22454. }
  22455. }
  22456. return this;
  22457. };
  22458. /**
  22459. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22460. * @param attachUp defines if you want to attach events to pointerup
  22461. * @param attachDown defines if you want to attach events to pointerdown
  22462. * @param attachMove defines if you want to attach events to pointermove
  22463. */
  22464. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22465. var _this = this;
  22466. if (attachUp === void 0) { attachUp = true; }
  22467. if (attachDown === void 0) { attachDown = true; }
  22468. if (attachMove === void 0) { attachMove = true; }
  22469. this._initActionManager = function (act, clickInfo) {
  22470. if (!_this._meshPickProceed) {
  22471. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22472. _this._currentPickResult = pickResult;
  22473. if (pickResult) {
  22474. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22475. }
  22476. _this._meshPickProceed = true;
  22477. }
  22478. return act;
  22479. };
  22480. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22481. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22482. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22483. btn !== _this._previousButtonPressed) {
  22484. _this._doubleClickOccured = false;
  22485. clickInfo.singleClick = true;
  22486. clickInfo.ignore = false;
  22487. cb(clickInfo, _this._currentPickResult);
  22488. }
  22489. };
  22490. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22491. var clickInfo = new ClickInfo();
  22492. _this._currentPickResult = null;
  22493. var act = null;
  22494. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22495. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22496. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22497. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22498. act = _this._initActionManager(act, clickInfo);
  22499. if (act)
  22500. checkPicking = act.hasPickTriggers;
  22501. }
  22502. if (checkPicking) {
  22503. var btn = evt.button;
  22504. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22505. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22506. if (!clickInfo.hasSwiped) {
  22507. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22508. if (!checkSingleClickImmediately) {
  22509. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22510. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22511. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22512. act = _this._initActionManager(act, clickInfo);
  22513. if (act)
  22514. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22515. }
  22516. }
  22517. if (checkSingleClickImmediately) {
  22518. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22519. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22520. btn !== _this._previousButtonPressed) {
  22521. clickInfo.singleClick = true;
  22522. cb(clickInfo, _this._currentPickResult);
  22523. }
  22524. }
  22525. else {
  22526. // wait that no double click has been raised during the double click delay
  22527. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22528. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22529. }
  22530. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22531. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22532. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22533. act = _this._initActionManager(act, clickInfo);
  22534. if (act)
  22535. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22536. }
  22537. if (checkDoubleClick) {
  22538. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22539. if (btn === _this._previousButtonPressed &&
  22540. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22541. !_this._doubleClickOccured) {
  22542. // pointer has not moved for 2 clicks, it's a double click
  22543. if (!clickInfo.hasSwiped &&
  22544. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22545. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22546. _this._previousStartingPointerTime = 0;
  22547. _this._doubleClickOccured = true;
  22548. clickInfo.doubleClick = true;
  22549. clickInfo.ignore = false;
  22550. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22551. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22552. }
  22553. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22554. cb(clickInfo, _this._currentPickResult);
  22555. }
  22556. else {
  22557. _this._doubleClickOccured = false;
  22558. _this._previousStartingPointerTime = _this._startingPointerTime;
  22559. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22560. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22561. _this._previousButtonPressed = btn;
  22562. if (Scene.ExclusiveDoubleClickMode) {
  22563. if (_this._previousDelayedSimpleClickTimeout) {
  22564. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22565. }
  22566. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22567. cb(clickInfo, _this._previousPickResult);
  22568. }
  22569. else {
  22570. cb(clickInfo, _this._currentPickResult);
  22571. }
  22572. }
  22573. }
  22574. else {
  22575. _this._doubleClickOccured = false;
  22576. _this._previousStartingPointerTime = _this._startingPointerTime;
  22577. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22578. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22579. _this._previousButtonPressed = btn;
  22580. }
  22581. }
  22582. }
  22583. }
  22584. clickInfo.ignore = true;
  22585. cb(clickInfo, _this._currentPickResult);
  22586. };
  22587. this._spritePredicate = function (sprite) {
  22588. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22589. };
  22590. this._onPointerMove = function (evt) {
  22591. _this._updatePointerPosition(evt);
  22592. // PreObservable support
  22593. if (_this.onPrePointerObservable.hasObservers()) {
  22594. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22595. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22596. _this.onPrePointerObservable.notifyObservers(pi, type);
  22597. if (pi.skipOnPointerObservable) {
  22598. return;
  22599. }
  22600. }
  22601. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22602. return;
  22603. }
  22604. if (!_this.pointerMovePredicate) {
  22605. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22606. }
  22607. // Meshes
  22608. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22609. _this._processPointerMove(pickResult, evt);
  22610. };
  22611. this._onPointerDown = function (evt) {
  22612. _this._totalPointersPressed++;
  22613. _this._pickedDownMesh = null;
  22614. _this._meshPickProceed = false;
  22615. _this._updatePointerPosition(evt);
  22616. if (_this.preventDefaultOnPointerDown && canvas) {
  22617. evt.preventDefault();
  22618. canvas.focus();
  22619. }
  22620. // PreObservable support
  22621. if (_this.onPrePointerObservable.hasObservers()) {
  22622. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22623. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22624. _this.onPrePointerObservable.notifyObservers(pi, type);
  22625. if (pi.skipOnPointerObservable) {
  22626. return;
  22627. }
  22628. }
  22629. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22630. return;
  22631. }
  22632. _this._startingPointerPosition.x = _this._pointerX;
  22633. _this._startingPointerPosition.y = _this._pointerY;
  22634. _this._startingPointerTime = new Date().getTime();
  22635. if (!_this.pointerDownPredicate) {
  22636. _this.pointerDownPredicate = function (mesh) {
  22637. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22638. };
  22639. }
  22640. // Meshes
  22641. _this._pickedDownMesh = null;
  22642. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22643. _this._processPointerDown(pickResult, evt);
  22644. // Sprites
  22645. _this._pickedDownSprite = null;
  22646. if (_this.spriteManagers.length > 0) {
  22647. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22648. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22649. if (pickResult.pickedSprite.actionManager) {
  22650. _this._pickedDownSprite = pickResult.pickedSprite;
  22651. switch (evt.button) {
  22652. case 0:
  22653. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22654. break;
  22655. case 1:
  22656. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22657. break;
  22658. case 2:
  22659. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22660. break;
  22661. }
  22662. if (pickResult.pickedSprite.actionManager) {
  22663. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22664. }
  22665. }
  22666. }
  22667. }
  22668. };
  22669. this._onPointerUp = function (evt) {
  22670. if (_this._totalPointersPressed === 0) {
  22671. return; // So we need to test it the pointer down was pressed before.
  22672. }
  22673. _this._totalPointersPressed--;
  22674. _this._pickedUpMesh = null;
  22675. _this._meshPickProceed = false;
  22676. _this._updatePointerPosition(evt);
  22677. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22678. // PreObservable support
  22679. if (_this.onPrePointerObservable.hasObservers()) {
  22680. if (!clickInfo.ignore) {
  22681. if (!clickInfo.hasSwiped) {
  22682. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22683. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22684. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22685. _this.onPrePointerObservable.notifyObservers(pi, type);
  22686. if (pi.skipOnPointerObservable) {
  22687. return;
  22688. }
  22689. }
  22690. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22691. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22692. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22693. _this.onPrePointerObservable.notifyObservers(pi, type);
  22694. if (pi.skipOnPointerObservable) {
  22695. return;
  22696. }
  22697. }
  22698. }
  22699. }
  22700. else {
  22701. var type = BABYLON.PointerEventTypes.POINTERUP;
  22702. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22703. _this.onPrePointerObservable.notifyObservers(pi, type);
  22704. if (pi.skipOnPointerObservable) {
  22705. return;
  22706. }
  22707. }
  22708. }
  22709. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22710. return;
  22711. }
  22712. if (!_this.pointerUpPredicate) {
  22713. _this.pointerUpPredicate = function (mesh) {
  22714. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22715. };
  22716. }
  22717. // Meshes
  22718. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22719. _this._initActionManager(null, clickInfo);
  22720. }
  22721. if (!pickResult) {
  22722. pickResult = _this._currentPickResult;
  22723. }
  22724. _this._processPointerUp(pickResult, evt, clickInfo);
  22725. // Sprites
  22726. if (_this.spriteManagers.length > 0) {
  22727. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22728. if (spritePickResult) {
  22729. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22730. if (spritePickResult.pickedSprite.actionManager) {
  22731. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22732. if (spritePickResult.pickedSprite.actionManager) {
  22733. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22734. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22735. }
  22736. }
  22737. }
  22738. }
  22739. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22740. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22741. }
  22742. }
  22743. }
  22744. _this._previousPickResult = _this._currentPickResult;
  22745. });
  22746. };
  22747. this._onKeyDown = function (evt) {
  22748. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22749. if (_this.onPreKeyboardObservable.hasObservers()) {
  22750. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22751. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22752. if (pi.skipOnPointerObservable) {
  22753. return;
  22754. }
  22755. }
  22756. if (_this.onKeyboardObservable.hasObservers()) {
  22757. var pi = new BABYLON.KeyboardInfo(type, evt);
  22758. _this.onKeyboardObservable.notifyObservers(pi, type);
  22759. }
  22760. if (_this.actionManager) {
  22761. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22762. }
  22763. };
  22764. this._onKeyUp = function (evt) {
  22765. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22766. if (_this.onPreKeyboardObservable.hasObservers()) {
  22767. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22768. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22769. if (pi.skipOnPointerObservable) {
  22770. return;
  22771. }
  22772. }
  22773. if (_this.onKeyboardObservable.hasObservers()) {
  22774. var pi = new BABYLON.KeyboardInfo(type, evt);
  22775. _this.onKeyboardObservable.notifyObservers(pi, type);
  22776. }
  22777. if (_this.actionManager) {
  22778. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22779. }
  22780. };
  22781. var engine = this.getEngine();
  22782. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22783. if (!canvas) {
  22784. return;
  22785. }
  22786. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22787. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22788. });
  22789. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22790. if (!canvas) {
  22791. return;
  22792. }
  22793. canvas.removeEventListener("keydown", _this._onKeyDown);
  22794. canvas.removeEventListener("keyup", _this._onKeyUp);
  22795. });
  22796. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22797. var canvas = this._engine.getRenderingCanvas();
  22798. if (!canvas) {
  22799. return;
  22800. }
  22801. if (attachMove) {
  22802. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22803. // Wheel
  22804. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22805. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22806. }
  22807. if (attachDown) {
  22808. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22809. }
  22810. if (attachUp) {
  22811. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22812. }
  22813. canvas.tabIndex = 1;
  22814. };
  22815. Scene.prototype.detachControl = function () {
  22816. var engine = this.getEngine();
  22817. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22818. var canvas = engine.getRenderingCanvas();
  22819. if (!canvas) {
  22820. return;
  22821. }
  22822. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22823. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22824. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22825. if (this._onCanvasBlurObserver) {
  22826. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22827. }
  22828. if (this._onCanvasFocusObserver) {
  22829. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22830. }
  22831. // Wheel
  22832. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22833. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22834. // Keyboard
  22835. canvas.removeEventListener("keydown", this._onKeyDown);
  22836. canvas.removeEventListener("keyup", this._onKeyUp);
  22837. // Observables
  22838. this.onKeyboardObservable.clear();
  22839. this.onPreKeyboardObservable.clear();
  22840. this.onPointerObservable.clear();
  22841. this.onPrePointerObservable.clear();
  22842. };
  22843. /**
  22844. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22845. * Delay loaded resources are not taking in account
  22846. * @return true if all required resources are ready
  22847. */
  22848. Scene.prototype.isReady = function () {
  22849. if (this._isDisposed) {
  22850. return false;
  22851. }
  22852. if (this._pendingData.length > 0) {
  22853. return false;
  22854. }
  22855. var index;
  22856. var engine = this.getEngine();
  22857. // Geometries
  22858. for (index = 0; index < this._geometries.length; index++) {
  22859. var geometry = this._geometries[index];
  22860. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22861. return false;
  22862. }
  22863. }
  22864. // Meshes
  22865. for (index = 0; index < this.meshes.length; index++) {
  22866. var mesh = this.meshes[index];
  22867. if (!mesh.isEnabled()) {
  22868. continue;
  22869. }
  22870. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22871. continue;
  22872. }
  22873. if (!mesh.isReady(true)) {
  22874. return false;
  22875. }
  22876. // Effect layers
  22877. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22878. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22879. var layer = _a[_i];
  22880. if (!layer.hasMesh(mesh)) {
  22881. continue;
  22882. }
  22883. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22884. var subMesh = _c[_b];
  22885. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22886. return false;
  22887. }
  22888. }
  22889. }
  22890. }
  22891. // Particles
  22892. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  22893. var particleSystem = _e[_d];
  22894. if (!particleSystem.isReady()) {
  22895. return false;
  22896. }
  22897. }
  22898. return true;
  22899. };
  22900. Scene.prototype.resetCachedMaterial = function () {
  22901. this._cachedMaterial = null;
  22902. this._cachedEffect = null;
  22903. this._cachedVisibility = null;
  22904. };
  22905. Scene.prototype.registerBeforeRender = function (func) {
  22906. this.onBeforeRenderObservable.add(func);
  22907. };
  22908. Scene.prototype.unregisterBeforeRender = function (func) {
  22909. this.onBeforeRenderObservable.removeCallback(func);
  22910. };
  22911. Scene.prototype.registerAfterRender = function (func) {
  22912. this.onAfterRenderObservable.add(func);
  22913. };
  22914. Scene.prototype.unregisterAfterRender = function (func) {
  22915. this.onAfterRenderObservable.removeCallback(func);
  22916. };
  22917. Scene.prototype._executeOnceBeforeRender = function (func) {
  22918. var _this = this;
  22919. var execFunc = function () {
  22920. func();
  22921. setTimeout(function () {
  22922. _this.unregisterBeforeRender(execFunc);
  22923. });
  22924. };
  22925. this.registerBeforeRender(execFunc);
  22926. };
  22927. /**
  22928. * The provided function will run before render once and will be disposed afterwards.
  22929. * A timeout delay can be provided so that the function will be executed in N ms.
  22930. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22931. * @param func The function to be executed.
  22932. * @param timeout optional delay in ms
  22933. */
  22934. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22935. var _this = this;
  22936. if (timeout !== undefined) {
  22937. setTimeout(function () {
  22938. _this._executeOnceBeforeRender(func);
  22939. }, timeout);
  22940. }
  22941. else {
  22942. this._executeOnceBeforeRender(func);
  22943. }
  22944. };
  22945. Scene.prototype._addPendingData = function (data) {
  22946. this._pendingData.push(data);
  22947. };
  22948. Scene.prototype._removePendingData = function (data) {
  22949. var wasLoading = this.isLoading;
  22950. var index = this._pendingData.indexOf(data);
  22951. if (index !== -1) {
  22952. this._pendingData.splice(index, 1);
  22953. }
  22954. if (wasLoading && !this.isLoading) {
  22955. this.onDataLoadedObservable.notifyObservers(this);
  22956. }
  22957. };
  22958. Scene.prototype.getWaitingItemsCount = function () {
  22959. return this._pendingData.length;
  22960. };
  22961. Object.defineProperty(Scene.prototype, "isLoading", {
  22962. get: function () {
  22963. return this._pendingData.length > 0;
  22964. },
  22965. enumerable: true,
  22966. configurable: true
  22967. });
  22968. /**
  22969. * Registers a function to be executed when the scene is ready.
  22970. * @param {Function} func - the function to be executed.
  22971. */
  22972. Scene.prototype.executeWhenReady = function (func) {
  22973. var _this = this;
  22974. this.onReadyObservable.add(func);
  22975. if (this._executeWhenReadyTimeoutId !== -1) {
  22976. return;
  22977. }
  22978. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22979. _this._checkIsReady();
  22980. }, 150);
  22981. };
  22982. /**
  22983. * Returns a promise that resolves when the scene is ready.
  22984. * @returns A promise that resolves when the scene is ready.
  22985. */
  22986. Scene.prototype.whenReadyAsync = function () {
  22987. var _this = this;
  22988. return new Promise(function (resolve) {
  22989. _this.executeWhenReady(function () {
  22990. resolve();
  22991. });
  22992. });
  22993. };
  22994. Scene.prototype._checkIsReady = function () {
  22995. var _this = this;
  22996. if (this.isReady()) {
  22997. this.onReadyObservable.notifyObservers(this);
  22998. this.onReadyObservable.clear();
  22999. this._executeWhenReadyTimeoutId = -1;
  23000. return;
  23001. }
  23002. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23003. _this._checkIsReady();
  23004. }, 150);
  23005. };
  23006. // Animations
  23007. /**
  23008. * Will start the animation sequence of a given target
  23009. * @param target - the target
  23010. * @param {number} from - from which frame should animation start
  23011. * @param {number} to - till which frame should animation run.
  23012. * @param {boolean} [loop] - should the animation loop
  23013. * @param {number} [speedRatio] - the speed in which to run the animation
  23014. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23015. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23016. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23017. * See BABYLON.Animatable
  23018. */
  23019. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23020. if (speedRatio === void 0) { speedRatio = 1.0; }
  23021. if (from > to && speedRatio > 0) {
  23022. speedRatio *= -1;
  23023. }
  23024. this.stopAnimation(target);
  23025. if (!animatable) {
  23026. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23027. }
  23028. // Local animations
  23029. if (target.animations) {
  23030. animatable.appendAnimations(target, target.animations);
  23031. }
  23032. // Children animations
  23033. if (target.getAnimatables) {
  23034. var animatables = target.getAnimatables();
  23035. for (var index = 0; index < animatables.length; index++) {
  23036. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23037. }
  23038. }
  23039. animatable.reset();
  23040. return animatable;
  23041. };
  23042. /**
  23043. * Begin a new animation on a given node
  23044. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23045. * @param {BABYLON.Animation[]} defines the list of animations to start
  23046. * @param {number} from defines the initial value
  23047. * @param {number} to defines the final value
  23048. * @param {boolean} loop defines if you want animation to loop (off by default)
  23049. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23050. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23051. * @returns the list of created animatables
  23052. */
  23053. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23054. if (speedRatio === undefined) {
  23055. speedRatio = 1.0;
  23056. }
  23057. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23058. return animatable;
  23059. };
  23060. /**
  23061. * Begin a new animation on a given node and its hierarchy
  23062. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23063. * @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.
  23064. * @param {BABYLON.Animation[]} defines the list of animations to start
  23065. * @param {number} from defines the initial value
  23066. * @param {number} to defines the final value
  23067. * @param {boolean} loop defines if you want animation to loop (off by default)
  23068. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23069. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23070. * @returns the list of animatables created for all nodes
  23071. */
  23072. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23073. var children = target.getDescendants(directDescendantsOnly);
  23074. var result = [];
  23075. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23076. var child = children_1[_i];
  23077. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23078. }
  23079. return result;
  23080. };
  23081. Scene.prototype.getAnimatableByTarget = function (target) {
  23082. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23083. if (this._activeAnimatables[index].target === target) {
  23084. return this._activeAnimatables[index];
  23085. }
  23086. }
  23087. return null;
  23088. };
  23089. Object.defineProperty(Scene.prototype, "animatables", {
  23090. get: function () {
  23091. return this._activeAnimatables;
  23092. },
  23093. enumerable: true,
  23094. configurable: true
  23095. });
  23096. /**
  23097. * Will stop the animation of the given target
  23098. * @param target - the target
  23099. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23100. * @see beginAnimation
  23101. */
  23102. Scene.prototype.stopAnimation = function (target, animationName) {
  23103. var animatable = this.getAnimatableByTarget(target);
  23104. if (animatable) {
  23105. animatable.stop(animationName);
  23106. }
  23107. };
  23108. /**
  23109. * Stops and removes all animations that have been applied to the scene
  23110. */
  23111. Scene.prototype.stopAllAnimations = function () {
  23112. if (this._activeAnimatables) {
  23113. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23114. this._activeAnimatables[i].stop();
  23115. }
  23116. this._activeAnimatables = [];
  23117. }
  23118. };
  23119. Scene.prototype._animate = function () {
  23120. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23121. return;
  23122. }
  23123. // Getting time
  23124. var now = BABYLON.Tools.Now;
  23125. if (!this._animationTimeLast) {
  23126. if (this._pendingData.length > 0) {
  23127. return;
  23128. }
  23129. this._animationTimeLast = now;
  23130. }
  23131. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23132. this._animationTime += deltaTime;
  23133. this._animationTimeLast = now;
  23134. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23135. this._activeAnimatables[index]._animate(this._animationTime);
  23136. }
  23137. };
  23138. // Matrix
  23139. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23140. this._useAlternateCameraConfiguration = active;
  23141. };
  23142. Scene.prototype.getViewMatrix = function () {
  23143. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23144. };
  23145. Scene.prototype.getProjectionMatrix = function () {
  23146. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23147. };
  23148. Scene.prototype.getTransformMatrix = function () {
  23149. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23150. };
  23151. Scene.prototype.setTransformMatrix = function (view, projection) {
  23152. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23153. return;
  23154. }
  23155. this._viewUpdateFlag = view.updateFlag;
  23156. this._projectionUpdateFlag = projection.updateFlag;
  23157. this._viewMatrix = view;
  23158. this._projectionMatrix = projection;
  23159. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23160. // Update frustum
  23161. if (!this._frustumPlanes) {
  23162. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23163. }
  23164. else {
  23165. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23166. }
  23167. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23168. var otherCamera = this.activeCamera._alternateCamera;
  23169. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23170. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23171. }
  23172. if (this._sceneUbo.useUbo) {
  23173. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23174. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23175. this._sceneUbo.update();
  23176. }
  23177. };
  23178. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23179. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23180. return;
  23181. }
  23182. this._alternateViewUpdateFlag = view.updateFlag;
  23183. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23184. this._alternateViewMatrix = view;
  23185. this._alternateProjectionMatrix = projection;
  23186. if (!this._alternateTransformMatrix) {
  23187. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23188. }
  23189. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23190. if (!this._alternateSceneUbo) {
  23191. this._createAlternateUbo();
  23192. }
  23193. if (this._alternateSceneUbo.useUbo) {
  23194. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23195. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23196. this._alternateSceneUbo.update();
  23197. }
  23198. };
  23199. Scene.prototype.getSceneUniformBuffer = function () {
  23200. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23201. };
  23202. // Methods
  23203. Scene.prototype.getUniqueId = function () {
  23204. var result = Scene._uniqueIdCounter;
  23205. Scene._uniqueIdCounter++;
  23206. return result;
  23207. };
  23208. Scene.prototype.addMesh = function (newMesh) {
  23209. this.meshes.push(newMesh);
  23210. //notify the collision coordinator
  23211. if (this.collisionCoordinator) {
  23212. this.collisionCoordinator.onMeshAdded(newMesh);
  23213. }
  23214. newMesh._resyncLightSources();
  23215. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23216. };
  23217. Scene.prototype.removeMesh = function (toRemove) {
  23218. var index = this.meshes.indexOf(toRemove);
  23219. if (index !== -1) {
  23220. // Remove from the scene if mesh found
  23221. this.meshes.splice(index, 1);
  23222. }
  23223. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23224. return index;
  23225. };
  23226. Scene.prototype.addTransformNode = function (newTransformNode) {
  23227. this.transformNodes.push(newTransformNode);
  23228. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23229. };
  23230. Scene.prototype.removeTransformNode = function (toRemove) {
  23231. var index = this.transformNodes.indexOf(toRemove);
  23232. if (index !== -1) {
  23233. // Remove from the scene if found
  23234. this.transformNodes.splice(index, 1);
  23235. }
  23236. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23237. return index;
  23238. };
  23239. Scene.prototype.removeSkeleton = function (toRemove) {
  23240. var index = this.skeletons.indexOf(toRemove);
  23241. if (index !== -1) {
  23242. // Remove from the scene if found
  23243. this.skeletons.splice(index, 1);
  23244. }
  23245. return index;
  23246. };
  23247. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23248. var index = this.morphTargetManagers.indexOf(toRemove);
  23249. if (index !== -1) {
  23250. // Remove from the scene if found
  23251. this.morphTargetManagers.splice(index, 1);
  23252. }
  23253. return index;
  23254. };
  23255. Scene.prototype.removeLight = function (toRemove) {
  23256. var index = this.lights.indexOf(toRemove);
  23257. if (index !== -1) {
  23258. // Remove from meshes
  23259. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23260. var mesh = _a[_i];
  23261. mesh._removeLightSource(toRemove);
  23262. }
  23263. // Remove from the scene if mesh found
  23264. this.lights.splice(index, 1);
  23265. this.sortLightsByPriority();
  23266. }
  23267. this.onLightRemovedObservable.notifyObservers(toRemove);
  23268. return index;
  23269. };
  23270. Scene.prototype.removeCamera = function (toRemove) {
  23271. var index = this.cameras.indexOf(toRemove);
  23272. if (index !== -1) {
  23273. // Remove from the scene if mesh found
  23274. this.cameras.splice(index, 1);
  23275. }
  23276. // Remove from activeCameras
  23277. var index2 = this.activeCameras.indexOf(toRemove);
  23278. if (index2 !== -1) {
  23279. // Remove from the scene if mesh found
  23280. this.activeCameras.splice(index2, 1);
  23281. }
  23282. // Reset the activeCamera
  23283. if (this.activeCamera === toRemove) {
  23284. if (this.cameras.length > 0) {
  23285. this.activeCamera = this.cameras[0];
  23286. }
  23287. else {
  23288. this.activeCamera = null;
  23289. }
  23290. }
  23291. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23292. return index;
  23293. };
  23294. Scene.prototype.removeParticleSystem = function (toRemove) {
  23295. var index = this.particleSystems.indexOf(toRemove);
  23296. if (index !== -1) {
  23297. this.particleSystems.splice(index, 1);
  23298. }
  23299. return index;
  23300. };
  23301. ;
  23302. Scene.prototype.removeAnimation = function (toRemove) {
  23303. var index = this.animations.indexOf(toRemove);
  23304. if (index !== -1) {
  23305. this.animations.splice(index, 1);
  23306. }
  23307. return index;
  23308. };
  23309. ;
  23310. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23311. var index = this.multiMaterials.indexOf(toRemove);
  23312. if (index !== -1) {
  23313. this.multiMaterials.splice(index, 1);
  23314. }
  23315. return index;
  23316. };
  23317. ;
  23318. Scene.prototype.removeMaterial = function (toRemove) {
  23319. var index = this.materials.indexOf(toRemove);
  23320. if (index !== -1) {
  23321. this.materials.splice(index, 1);
  23322. }
  23323. return index;
  23324. };
  23325. ;
  23326. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23327. var index = this.lensFlareSystems.indexOf(toRemove);
  23328. if (index !== -1) {
  23329. this.lensFlareSystems.splice(index, 1);
  23330. }
  23331. return index;
  23332. };
  23333. ;
  23334. Scene.prototype.removeActionManager = function (toRemove) {
  23335. var index = this._actionManagers.indexOf(toRemove);
  23336. if (index !== -1) {
  23337. this._actionManagers.splice(index, 1);
  23338. }
  23339. return index;
  23340. };
  23341. ;
  23342. Scene.prototype.addLight = function (newLight) {
  23343. this.lights.push(newLight);
  23344. this.sortLightsByPriority();
  23345. // Add light to all meshes (To support if the light is removed and then readded)
  23346. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23347. var mesh = _a[_i];
  23348. if (mesh._lightSources.indexOf(newLight) === -1) {
  23349. mesh._lightSources.push(newLight);
  23350. mesh._resyncLightSources();
  23351. }
  23352. }
  23353. this.onNewLightAddedObservable.notifyObservers(newLight);
  23354. };
  23355. Scene.prototype.sortLightsByPriority = function () {
  23356. if (this.requireLightSorting) {
  23357. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23358. }
  23359. };
  23360. Scene.prototype.addCamera = function (newCamera) {
  23361. this.cameras.push(newCamera);
  23362. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23363. };
  23364. Scene.prototype.addSkeleton = function (newSkeleton) {
  23365. this.skeletons.push(newSkeleton);
  23366. };
  23367. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23368. this.particleSystems.push(newParticleSystem);
  23369. };
  23370. Scene.prototype.addAnimation = function (newAnimation) {
  23371. this.animations.push(newAnimation);
  23372. };
  23373. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23374. this.multiMaterials.push(newMultiMaterial);
  23375. };
  23376. Scene.prototype.addMaterial = function (newMaterial) {
  23377. this.materials.push(newMaterial);
  23378. };
  23379. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23380. this.morphTargetManagers.push(newMorphTargetManager);
  23381. };
  23382. Scene.prototype.addGeometry = function (newGeometrie) {
  23383. this._geometries.push(newGeometrie);
  23384. };
  23385. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23386. this.lensFlareSystems.push(newLensFlareSystem);
  23387. };
  23388. Scene.prototype.addActionManager = function (newActionManager) {
  23389. this._actionManagers.push(newActionManager);
  23390. };
  23391. /**
  23392. * Switch active camera
  23393. * @param {Camera} newCamera - new active camera
  23394. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23395. */
  23396. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23397. if (attachControl === void 0) { attachControl = true; }
  23398. var canvas = this._engine.getRenderingCanvas();
  23399. if (!canvas) {
  23400. return;
  23401. }
  23402. if (this.activeCamera) {
  23403. this.activeCamera.detachControl(canvas);
  23404. }
  23405. this.activeCamera = newCamera;
  23406. if (attachControl) {
  23407. newCamera.attachControl(canvas);
  23408. }
  23409. };
  23410. /**
  23411. * sets the active camera of the scene using its ID
  23412. * @param {string} id - the camera's ID
  23413. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23414. * @see activeCamera
  23415. */
  23416. Scene.prototype.setActiveCameraByID = function (id) {
  23417. var camera = this.getCameraByID(id);
  23418. if (camera) {
  23419. this.activeCamera = camera;
  23420. return camera;
  23421. }
  23422. return null;
  23423. };
  23424. /**
  23425. * sets the active camera of the scene using its name
  23426. * @param {string} name - the camera's name
  23427. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23428. * @see activeCamera
  23429. */
  23430. Scene.prototype.setActiveCameraByName = function (name) {
  23431. var camera = this.getCameraByName(name);
  23432. if (camera) {
  23433. this.activeCamera = camera;
  23434. return camera;
  23435. }
  23436. return null;
  23437. };
  23438. /**
  23439. * get an animation group using its name
  23440. * @param {string} the material's name
  23441. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23442. */
  23443. Scene.prototype.getAnimationGroupByName = function (name) {
  23444. for (var index = 0; index < this.animationGroups.length; index++) {
  23445. if (this.animationGroups[index].name === name) {
  23446. return this.animationGroups[index];
  23447. }
  23448. }
  23449. return null;
  23450. };
  23451. /**
  23452. * get a material using its id
  23453. * @param {string} the material's ID
  23454. * @return {BABYLON.Material|null} the material or null if none found.
  23455. */
  23456. Scene.prototype.getMaterialByID = function (id) {
  23457. for (var index = 0; index < this.materials.length; index++) {
  23458. if (this.materials[index].id === id) {
  23459. return this.materials[index];
  23460. }
  23461. }
  23462. return null;
  23463. };
  23464. /**
  23465. * get a material using its name
  23466. * @param {string} the material's name
  23467. * @return {BABYLON.Material|null} the material or null if none found.
  23468. */
  23469. Scene.prototype.getMaterialByName = function (name) {
  23470. for (var index = 0; index < this.materials.length; index++) {
  23471. if (this.materials[index].name === name) {
  23472. return this.materials[index];
  23473. }
  23474. }
  23475. return null;
  23476. };
  23477. Scene.prototype.getLensFlareSystemByName = function (name) {
  23478. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23479. if (this.lensFlareSystems[index].name === name) {
  23480. return this.lensFlareSystems[index];
  23481. }
  23482. }
  23483. return null;
  23484. };
  23485. Scene.prototype.getLensFlareSystemByID = function (id) {
  23486. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23487. if (this.lensFlareSystems[index].id === id) {
  23488. return this.lensFlareSystems[index];
  23489. }
  23490. }
  23491. return null;
  23492. };
  23493. Scene.prototype.getCameraByID = function (id) {
  23494. for (var index = 0; index < this.cameras.length; index++) {
  23495. if (this.cameras[index].id === id) {
  23496. return this.cameras[index];
  23497. }
  23498. }
  23499. return null;
  23500. };
  23501. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23502. for (var index = 0; index < this.cameras.length; index++) {
  23503. if (this.cameras[index].uniqueId === uniqueId) {
  23504. return this.cameras[index];
  23505. }
  23506. }
  23507. return null;
  23508. };
  23509. /**
  23510. * get a camera using its name
  23511. * @param {string} the camera's name
  23512. * @return {BABYLON.Camera|null} the camera or null if none found.
  23513. */
  23514. Scene.prototype.getCameraByName = function (name) {
  23515. for (var index = 0; index < this.cameras.length; index++) {
  23516. if (this.cameras[index].name === name) {
  23517. return this.cameras[index];
  23518. }
  23519. }
  23520. return null;
  23521. };
  23522. /**
  23523. * get a bone using its id
  23524. * @param {string} the bone's id
  23525. * @return {BABYLON.Bone|null} the bone or null if not found
  23526. */
  23527. Scene.prototype.getBoneByID = function (id) {
  23528. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23529. var skeleton = this.skeletons[skeletonIndex];
  23530. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23531. if (skeleton.bones[boneIndex].id === id) {
  23532. return skeleton.bones[boneIndex];
  23533. }
  23534. }
  23535. }
  23536. return null;
  23537. };
  23538. /**
  23539. * get a bone using its id
  23540. * @param {string} the bone's name
  23541. * @return {BABYLON.Bone|null} the bone or null if not found
  23542. */
  23543. Scene.prototype.getBoneByName = function (name) {
  23544. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23545. var skeleton = this.skeletons[skeletonIndex];
  23546. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23547. if (skeleton.bones[boneIndex].name === name) {
  23548. return skeleton.bones[boneIndex];
  23549. }
  23550. }
  23551. }
  23552. return null;
  23553. };
  23554. /**
  23555. * get a light node using its name
  23556. * @param {string} the light's name
  23557. * @return {BABYLON.Light|null} the light or null if none found.
  23558. */
  23559. Scene.prototype.getLightByName = function (name) {
  23560. for (var index = 0; index < this.lights.length; index++) {
  23561. if (this.lights[index].name === name) {
  23562. return this.lights[index];
  23563. }
  23564. }
  23565. return null;
  23566. };
  23567. /**
  23568. * get a light node using its ID
  23569. * @param {string} the light's id
  23570. * @return {BABYLON.Light|null} the light or null if none found.
  23571. */
  23572. Scene.prototype.getLightByID = function (id) {
  23573. for (var index = 0; index < this.lights.length; index++) {
  23574. if (this.lights[index].id === id) {
  23575. return this.lights[index];
  23576. }
  23577. }
  23578. return null;
  23579. };
  23580. /**
  23581. * get a light node using its scene-generated unique ID
  23582. * @param {number} the light's unique id
  23583. * @return {BABYLON.Light|null} the light or null if none found.
  23584. */
  23585. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23586. for (var index = 0; index < this.lights.length; index++) {
  23587. if (this.lights[index].uniqueId === uniqueId) {
  23588. return this.lights[index];
  23589. }
  23590. }
  23591. return null;
  23592. };
  23593. /**
  23594. * get a particle system by id
  23595. * @param id {number} the particle system id
  23596. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23597. */
  23598. Scene.prototype.getParticleSystemByID = function (id) {
  23599. for (var index = 0; index < this.particleSystems.length; index++) {
  23600. if (this.particleSystems[index].id === id) {
  23601. return this.particleSystems[index];
  23602. }
  23603. }
  23604. return null;
  23605. };
  23606. /**
  23607. * get a geometry using its ID
  23608. * @param {string} the geometry's id
  23609. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23610. */
  23611. Scene.prototype.getGeometryByID = function (id) {
  23612. for (var index = 0; index < this._geometries.length; index++) {
  23613. if (this._geometries[index].id === id) {
  23614. return this._geometries[index];
  23615. }
  23616. }
  23617. return null;
  23618. };
  23619. /**
  23620. * add a new geometry to this scene.
  23621. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23622. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23623. * @return {boolean} was the geometry added or not
  23624. */
  23625. Scene.prototype.pushGeometry = function (geometry, force) {
  23626. if (!force && this.getGeometryByID(geometry.id)) {
  23627. return false;
  23628. }
  23629. this._geometries.push(geometry);
  23630. //notify the collision coordinator
  23631. if (this.collisionCoordinator) {
  23632. this.collisionCoordinator.onGeometryAdded(geometry);
  23633. }
  23634. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23635. return true;
  23636. };
  23637. /**
  23638. * Removes an existing geometry
  23639. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23640. * @return {boolean} was the geometry removed or not
  23641. */
  23642. Scene.prototype.removeGeometry = function (geometry) {
  23643. var index = this._geometries.indexOf(geometry);
  23644. if (index > -1) {
  23645. this._geometries.splice(index, 1);
  23646. //notify the collision coordinator
  23647. if (this.collisionCoordinator) {
  23648. this.collisionCoordinator.onGeometryDeleted(geometry);
  23649. }
  23650. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23651. return true;
  23652. }
  23653. return false;
  23654. };
  23655. Scene.prototype.getGeometries = function () {
  23656. return this._geometries;
  23657. };
  23658. /**
  23659. * Get the first added mesh found of a given ID
  23660. * @param {string} id - the id to search for
  23661. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23662. */
  23663. Scene.prototype.getMeshByID = function (id) {
  23664. for (var index = 0; index < this.meshes.length; index++) {
  23665. if (this.meshes[index].id === id) {
  23666. return this.meshes[index];
  23667. }
  23668. }
  23669. return null;
  23670. };
  23671. Scene.prototype.getMeshesByID = function (id) {
  23672. return this.meshes.filter(function (m) {
  23673. return m.id === id;
  23674. });
  23675. };
  23676. /**
  23677. * Get the first added transform node found of a given ID
  23678. * @param {string} id - the id to search for
  23679. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23680. */
  23681. Scene.prototype.getTransformNodeByID = function (id) {
  23682. for (var index = 0; index < this.transformNodes.length; index++) {
  23683. if (this.transformNodes[index].id === id) {
  23684. return this.transformNodes[index];
  23685. }
  23686. }
  23687. return null;
  23688. };
  23689. Scene.prototype.getTransformNodesByID = function (id) {
  23690. return this.transformNodes.filter(function (m) {
  23691. return m.id === id;
  23692. });
  23693. };
  23694. /**
  23695. * Get a mesh with its auto-generated unique id
  23696. * @param {number} uniqueId - the unique id to search for
  23697. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23698. */
  23699. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23700. for (var index = 0; index < this.meshes.length; index++) {
  23701. if (this.meshes[index].uniqueId === uniqueId) {
  23702. return this.meshes[index];
  23703. }
  23704. }
  23705. return null;
  23706. };
  23707. /**
  23708. * Get a the last added mesh found of a given ID
  23709. * @param {string} id - the id to search for
  23710. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23711. */
  23712. Scene.prototype.getLastMeshByID = function (id) {
  23713. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23714. if (this.meshes[index].id === id) {
  23715. return this.meshes[index];
  23716. }
  23717. }
  23718. return null;
  23719. };
  23720. /**
  23721. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23722. * @param {string} id - the id to search for
  23723. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23724. */
  23725. Scene.prototype.getLastEntryByID = function (id) {
  23726. var index;
  23727. for (index = this.meshes.length - 1; index >= 0; index--) {
  23728. if (this.meshes[index].id === id) {
  23729. return this.meshes[index];
  23730. }
  23731. }
  23732. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23733. if (this.transformNodes[index].id === id) {
  23734. return this.transformNodes[index];
  23735. }
  23736. }
  23737. for (index = this.cameras.length - 1; index >= 0; index--) {
  23738. if (this.cameras[index].id === id) {
  23739. return this.cameras[index];
  23740. }
  23741. }
  23742. for (index = this.lights.length - 1; index >= 0; index--) {
  23743. if (this.lights[index].id === id) {
  23744. return this.lights[index];
  23745. }
  23746. }
  23747. return null;
  23748. };
  23749. Scene.prototype.getNodeByID = function (id) {
  23750. var mesh = this.getMeshByID(id);
  23751. if (mesh) {
  23752. return mesh;
  23753. }
  23754. var light = this.getLightByID(id);
  23755. if (light) {
  23756. return light;
  23757. }
  23758. var camera = this.getCameraByID(id);
  23759. if (camera) {
  23760. return camera;
  23761. }
  23762. var bone = this.getBoneByID(id);
  23763. return bone;
  23764. };
  23765. Scene.prototype.getNodeByName = function (name) {
  23766. var mesh = this.getMeshByName(name);
  23767. if (mesh) {
  23768. return mesh;
  23769. }
  23770. var light = this.getLightByName(name);
  23771. if (light) {
  23772. return light;
  23773. }
  23774. var camera = this.getCameraByName(name);
  23775. if (camera) {
  23776. return camera;
  23777. }
  23778. var bone = this.getBoneByName(name);
  23779. return bone;
  23780. };
  23781. Scene.prototype.getMeshByName = function (name) {
  23782. for (var index = 0; index < this.meshes.length; index++) {
  23783. if (this.meshes[index].name === name) {
  23784. return this.meshes[index];
  23785. }
  23786. }
  23787. return null;
  23788. };
  23789. Scene.prototype.getTransformNodeByName = function (name) {
  23790. for (var index = 0; index < this.transformNodes.length; index++) {
  23791. if (this.transformNodes[index].name === name) {
  23792. return this.transformNodes[index];
  23793. }
  23794. }
  23795. return null;
  23796. };
  23797. Scene.prototype.getSoundByName = function (name) {
  23798. var index;
  23799. if (BABYLON.AudioEngine) {
  23800. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23801. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23802. return this.mainSoundTrack.soundCollection[index];
  23803. }
  23804. }
  23805. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23806. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23807. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23808. return this.soundTracks[sdIndex].soundCollection[index];
  23809. }
  23810. }
  23811. }
  23812. }
  23813. return null;
  23814. };
  23815. Scene.prototype.getLastSkeletonByID = function (id) {
  23816. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23817. if (this.skeletons[index].id === id) {
  23818. return this.skeletons[index];
  23819. }
  23820. }
  23821. return null;
  23822. };
  23823. Scene.prototype.getSkeletonById = function (id) {
  23824. for (var index = 0; index < this.skeletons.length; index++) {
  23825. if (this.skeletons[index].id === id) {
  23826. return this.skeletons[index];
  23827. }
  23828. }
  23829. return null;
  23830. };
  23831. Scene.prototype.getSkeletonByName = function (name) {
  23832. for (var index = 0; index < this.skeletons.length; index++) {
  23833. if (this.skeletons[index].name === name) {
  23834. return this.skeletons[index];
  23835. }
  23836. }
  23837. return null;
  23838. };
  23839. Scene.prototype.getMorphTargetManagerById = function (id) {
  23840. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23841. if (this.morphTargetManagers[index].uniqueId === id) {
  23842. return this.morphTargetManagers[index];
  23843. }
  23844. }
  23845. return null;
  23846. };
  23847. Scene.prototype.isActiveMesh = function (mesh) {
  23848. return (this._activeMeshes.indexOf(mesh) !== -1);
  23849. };
  23850. /**
  23851. * Return a the first highlight layer of the scene with a given name.
  23852. * @param name The name of the highlight layer to look for.
  23853. * @return The highlight layer if found otherwise null.
  23854. */
  23855. Scene.prototype.getHighlightLayerByName = function (name) {
  23856. for (var index = 0; index < this.effectLayers.length; index++) {
  23857. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23858. return this.effectLayers[index];
  23859. }
  23860. }
  23861. return null;
  23862. };
  23863. /**
  23864. * Return a the first highlight layer of the scene with a given name.
  23865. * @param name The name of the highlight layer to look for.
  23866. * @return The highlight layer if found otherwise null.
  23867. */
  23868. Scene.prototype.getGlowLayerByName = function (name) {
  23869. for (var index = 0; index < this.effectLayers.length; index++) {
  23870. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23871. return this.effectLayers[index];
  23872. }
  23873. }
  23874. return null;
  23875. };
  23876. Object.defineProperty(Scene.prototype, "uid", {
  23877. /**
  23878. * Return a unique id as a string which can serve as an identifier for the scene
  23879. */
  23880. get: function () {
  23881. if (!this._uid) {
  23882. this._uid = BABYLON.Tools.RandomId();
  23883. }
  23884. return this._uid;
  23885. },
  23886. enumerable: true,
  23887. configurable: true
  23888. });
  23889. /**
  23890. * Add an externaly attached data from its key.
  23891. * This method call will fail and return false, if such key already exists.
  23892. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23893. * @param key the unique key that identifies the data
  23894. * @param data the data object to associate to the key for this Engine instance
  23895. * @return true if no such key were already present and the data was added successfully, false otherwise
  23896. */
  23897. Scene.prototype.addExternalData = function (key, data) {
  23898. if (!this._externalData) {
  23899. this._externalData = new BABYLON.StringDictionary();
  23900. }
  23901. return this._externalData.add(key, data);
  23902. };
  23903. /**
  23904. * Get an externaly attached data from its key
  23905. * @param key the unique key that identifies the data
  23906. * @return the associated data, if present (can be null), or undefined if not present
  23907. */
  23908. Scene.prototype.getExternalData = function (key) {
  23909. if (!this._externalData) {
  23910. return null;
  23911. }
  23912. return this._externalData.get(key);
  23913. };
  23914. /**
  23915. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23916. * @param key the unique key that identifies the data
  23917. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23918. * @return the associated data, can be null if the factory returned null.
  23919. */
  23920. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23921. if (!this._externalData) {
  23922. this._externalData = new BABYLON.StringDictionary();
  23923. }
  23924. return this._externalData.getOrAddWithFactory(key, factory);
  23925. };
  23926. /**
  23927. * Remove an externaly attached data from the Engine instance
  23928. * @param key the unique key that identifies the data
  23929. * @return true if the data was successfully removed, false if it doesn't exist
  23930. */
  23931. Scene.prototype.removeExternalData = function (key) {
  23932. return this._externalData.remove(key);
  23933. };
  23934. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23935. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23936. if (mesh.showSubMeshesBoundingBox) {
  23937. var boundingInfo = subMesh.getBoundingInfo();
  23938. if (boundingInfo !== null && boundingInfo !== undefined) {
  23939. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23940. }
  23941. }
  23942. var material = subMesh.getMaterial();
  23943. if (material !== null && material !== undefined) {
  23944. // Render targets
  23945. if (material.getRenderTargetTextures !== undefined) {
  23946. if (this._processedMaterials.indexOf(material) === -1) {
  23947. this._processedMaterials.push(material);
  23948. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23949. }
  23950. }
  23951. // Dispatch
  23952. this._activeIndices.addCount(subMesh.indexCount, false);
  23953. this._renderingManager.dispatch(subMesh, mesh, material);
  23954. }
  23955. }
  23956. };
  23957. /**
  23958. * Clear the processed materials smart array preventing retention point in material dispose.
  23959. */
  23960. Scene.prototype.freeProcessedMaterials = function () {
  23961. this._processedMaterials.dispose();
  23962. };
  23963. /**
  23964. * Clear the active meshes smart array preventing retention point in mesh dispose.
  23965. */
  23966. Scene.prototype.freeActiveMeshes = function () {
  23967. this._activeMeshes.dispose();
  23968. if (this.activeCamera && this.activeCamera._activeMeshes) {
  23969. this.activeCamera._activeMeshes.dispose();
  23970. }
  23971. if (this.activeCameras) {
  23972. for (var i = 0; i < this.activeCameras.length; i++) {
  23973. var activeCamera = this.activeCameras[i];
  23974. if (activeCamera && activeCamera._activeMeshes) {
  23975. activeCamera._activeMeshes.dispose();
  23976. }
  23977. }
  23978. }
  23979. };
  23980. /**
  23981. * Clear the info related to rendering groups preventing retention points during dispose.
  23982. */
  23983. Scene.prototype.freeRenderingGroups = function () {
  23984. if (this._renderingManager) {
  23985. this._renderingManager.freeRenderingGroups();
  23986. }
  23987. if (this.textures) {
  23988. for (var i = 0; i < this.textures.length; i++) {
  23989. var texture = this.textures[i];
  23990. if (texture && texture.renderList) {
  23991. texture.freeRenderingGroups();
  23992. }
  23993. }
  23994. }
  23995. };
  23996. Scene.prototype._isInIntermediateRendering = function () {
  23997. return this._intermediateRendering;
  23998. };
  23999. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24000. this._activeMeshCandidateProvider = provider;
  24001. };
  24002. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24003. return this._activeMeshCandidateProvider;
  24004. };
  24005. /**
  24006. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24007. */
  24008. Scene.prototype.freezeActiveMeshes = function () {
  24009. this._evaluateActiveMeshes();
  24010. this._activeMeshesFrozen = true;
  24011. return this;
  24012. };
  24013. /**
  24014. * Use this function to restart evaluating active meshes on every frame
  24015. */
  24016. Scene.prototype.unfreezeActiveMeshes = function () {
  24017. this._activeMeshesFrozen = false;
  24018. return this;
  24019. };
  24020. Scene.prototype._evaluateActiveMeshes = function () {
  24021. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24022. return;
  24023. }
  24024. if (!this.activeCamera) {
  24025. return;
  24026. }
  24027. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24028. this.activeCamera._activeMeshes.reset();
  24029. this._activeMeshes.reset();
  24030. this._renderingManager.reset();
  24031. this._processedMaterials.reset();
  24032. this._activeParticleSystems.reset();
  24033. this._activeSkeletons.reset();
  24034. this._softwareSkinnedMeshes.reset();
  24035. if (this._boundingBoxRenderer) {
  24036. this._boundingBoxRenderer.reset();
  24037. }
  24038. // Meshes
  24039. var meshes;
  24040. var len;
  24041. var checkIsEnabled = true;
  24042. // Determine mesh candidates
  24043. if (this._activeMeshCandidateProvider !== undefined) {
  24044. // Use _activeMeshCandidateProvider
  24045. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24046. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24047. if (meshes !== undefined) {
  24048. len = meshes.length;
  24049. }
  24050. else {
  24051. len = 0;
  24052. }
  24053. }
  24054. else if (this._selectionOctree !== undefined) {
  24055. // Octree
  24056. var selection = this._selectionOctree.select(this._frustumPlanes);
  24057. meshes = selection.data;
  24058. len = selection.length;
  24059. }
  24060. else {
  24061. // Full scene traversal
  24062. len = this.meshes.length;
  24063. meshes = this.meshes;
  24064. }
  24065. // Check each mesh
  24066. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24067. mesh = meshes[meshIndex];
  24068. if (mesh.isBlocked) {
  24069. continue;
  24070. }
  24071. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24072. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24073. continue;
  24074. }
  24075. mesh.computeWorldMatrix();
  24076. // Intersections
  24077. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24078. this._meshesForIntersections.pushNoDuplicate(mesh);
  24079. }
  24080. // Switch to current LOD
  24081. meshLOD = mesh.getLOD(this.activeCamera);
  24082. if (meshLOD === undefined || meshLOD === null) {
  24083. continue;
  24084. }
  24085. mesh._preActivate();
  24086. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24087. this._activeMeshes.push(mesh);
  24088. this.activeCamera._activeMeshes.push(mesh);
  24089. mesh._activate(this._renderId);
  24090. if (meshLOD !== mesh) {
  24091. meshLOD._activate(this._renderId);
  24092. }
  24093. this._activeMesh(mesh, meshLOD);
  24094. }
  24095. }
  24096. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24097. // Particle systems
  24098. if (this.particlesEnabled) {
  24099. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24100. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24101. var particleSystem = this.particleSystems[particleIndex];
  24102. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24103. continue;
  24104. }
  24105. var emitter = particleSystem.emitter;
  24106. if (!emitter.position || emitter.isEnabled()) {
  24107. this._activeParticleSystems.push(particleSystem);
  24108. particleSystem.animate();
  24109. this._renderingManager.dispatchParticles(particleSystem);
  24110. }
  24111. }
  24112. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24113. }
  24114. };
  24115. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24116. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24117. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24118. mesh.skeleton.prepare();
  24119. }
  24120. if (!mesh.computeBonesUsingShaders) {
  24121. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24122. }
  24123. }
  24124. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24125. var boundingInfo = sourceMesh.getBoundingInfo();
  24126. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24127. }
  24128. if (mesh !== undefined && mesh !== null
  24129. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24130. // Submeshes Octrees
  24131. var len;
  24132. var subMeshes;
  24133. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24134. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24135. len = intersections.length;
  24136. subMeshes = intersections.data;
  24137. }
  24138. else {
  24139. subMeshes = mesh.subMeshes;
  24140. len = subMeshes.length;
  24141. }
  24142. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24143. subMesh = subMeshes[subIndex];
  24144. this._evaluateSubMesh(subMesh, mesh);
  24145. }
  24146. }
  24147. };
  24148. Scene.prototype.updateTransformMatrix = function (force) {
  24149. if (!this.activeCamera) {
  24150. return;
  24151. }
  24152. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24153. };
  24154. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24155. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24156. };
  24157. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24158. if (camera && camera._skipRendering) {
  24159. return;
  24160. }
  24161. var engine = this._engine;
  24162. this.activeCamera = camera;
  24163. if (!this.activeCamera)
  24164. throw new Error("Active camera not set");
  24165. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24166. // Viewport
  24167. engine.setViewport(this.activeCamera.viewport);
  24168. // Camera
  24169. this.resetCachedMaterial();
  24170. this._renderId++;
  24171. this.updateTransformMatrix();
  24172. if (camera._alternateCamera) {
  24173. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24174. this._alternateRendering = true;
  24175. }
  24176. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24177. // Meshes
  24178. this._evaluateActiveMeshes();
  24179. // Software skinning
  24180. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24181. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24182. mesh.applySkeleton(mesh.skeleton);
  24183. }
  24184. // Render targets
  24185. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24186. var needsRestoreFrameBuffer = false;
  24187. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24188. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24189. }
  24190. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24191. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24192. }
  24193. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24194. this._intermediateRendering = true;
  24195. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24196. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24197. var renderTarget = this._renderTargets.data[renderIndex];
  24198. if (renderTarget._shouldRender()) {
  24199. this._renderId++;
  24200. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24201. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24202. }
  24203. }
  24204. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24205. this._intermediateRendering = false;
  24206. this._renderId++;
  24207. needsRestoreFrameBuffer = true; // Restore back buffer
  24208. }
  24209. // Render EffecttLayer Texture
  24210. var stencilState = this._engine.getStencilBuffer();
  24211. var renderEffects = false;
  24212. var needStencil = false;
  24213. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24214. this._intermediateRendering = true;
  24215. for (var i = 0; i < this.effectLayers.length; i++) {
  24216. var effectLayer = this.effectLayers[i];
  24217. if (effectLayer.shouldRender() &&
  24218. (!effectLayer.camera ||
  24219. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24220. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24221. renderEffects = true;
  24222. needStencil = needStencil || effectLayer.needStencil();
  24223. var renderTarget = effectLayer._mainTexture;
  24224. if (renderTarget._shouldRender()) {
  24225. this._renderId++;
  24226. renderTarget.render(false, false);
  24227. needsRestoreFrameBuffer = true;
  24228. }
  24229. }
  24230. }
  24231. this._intermediateRendering = false;
  24232. this._renderId++;
  24233. }
  24234. if (needsRestoreFrameBuffer) {
  24235. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24236. }
  24237. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24238. // Prepare Frame
  24239. this.postProcessManager._prepareFrame();
  24240. // Backgrounds
  24241. var layerIndex;
  24242. var layer;
  24243. if (this.layers.length) {
  24244. engine.setDepthBuffer(false);
  24245. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24246. layer = this.layers[layerIndex];
  24247. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24248. layer.render();
  24249. }
  24250. }
  24251. engine.setDepthBuffer(true);
  24252. }
  24253. // Activate effect Layer stencil
  24254. if (needStencil) {
  24255. this._engine.setStencilBuffer(true);
  24256. }
  24257. // Render
  24258. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24259. this._renderingManager.render(null, null, true, true);
  24260. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24261. // Restore effect Layer stencil
  24262. if (needStencil) {
  24263. this._engine.setStencilBuffer(stencilState);
  24264. }
  24265. // Bounding boxes
  24266. if (this._boundingBoxRenderer) {
  24267. this._boundingBoxRenderer.render();
  24268. }
  24269. // Lens flares
  24270. if (this.lensFlaresEnabled) {
  24271. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24272. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24273. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24274. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24275. lensFlareSystem.render();
  24276. }
  24277. }
  24278. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24279. }
  24280. // Foregrounds
  24281. if (this.layers.length) {
  24282. engine.setDepthBuffer(false);
  24283. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24284. layer = this.layers[layerIndex];
  24285. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24286. layer.render();
  24287. }
  24288. }
  24289. engine.setDepthBuffer(true);
  24290. }
  24291. // Effect Layer
  24292. if (renderEffects) {
  24293. engine.setDepthBuffer(false);
  24294. for (var i = 0; i < this.effectLayers.length; i++) {
  24295. if (this.effectLayers[i].shouldRender()) {
  24296. this.effectLayers[i].render();
  24297. }
  24298. }
  24299. engine.setDepthBuffer(true);
  24300. }
  24301. // Finalize frame
  24302. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24303. // Reset some special arrays
  24304. this._renderTargets.reset();
  24305. this._alternateRendering = false;
  24306. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24307. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24308. };
  24309. Scene.prototype._processSubCameras = function (camera) {
  24310. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24311. this._renderForCamera(camera);
  24312. return;
  24313. }
  24314. // rig cameras
  24315. for (var index = 0; index < camera._rigCameras.length; index++) {
  24316. this._renderForCamera(camera._rigCameras[index], camera);
  24317. }
  24318. this.activeCamera = camera;
  24319. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24320. };
  24321. Scene.prototype._checkIntersections = function () {
  24322. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24323. var sourceMesh = this._meshesForIntersections.data[index];
  24324. if (!sourceMesh.actionManager) {
  24325. continue;
  24326. }
  24327. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24328. var action = sourceMesh.actionManager.actions[actionIndex];
  24329. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24330. var parameters = action.getTriggerParameter();
  24331. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24332. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24333. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24334. if (areIntersecting && currentIntersectionInProgress === -1) {
  24335. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24336. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24337. sourceMesh._intersectionsInProgress.push(otherMesh);
  24338. }
  24339. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24340. sourceMesh._intersectionsInProgress.push(otherMesh);
  24341. }
  24342. }
  24343. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24344. //They intersected, and now they don't.
  24345. //is this trigger an exit trigger? execute an event.
  24346. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24347. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24348. }
  24349. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24350. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24351. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24352. }
  24353. }
  24354. }
  24355. }
  24356. }
  24357. };
  24358. Scene.prototype.render = function () {
  24359. if (this.isDisposed) {
  24360. return;
  24361. }
  24362. this._activeParticles.fetchNewFrame();
  24363. this._totalVertices.fetchNewFrame();
  24364. this._activeIndices.fetchNewFrame();
  24365. this._activeBones.fetchNewFrame();
  24366. this._meshesForIntersections.reset();
  24367. this.resetCachedMaterial();
  24368. this.onBeforeAnimationsObservable.notifyObservers(this);
  24369. // Actions
  24370. if (this.actionManager) {
  24371. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24372. }
  24373. //Simplification Queue
  24374. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24375. this.simplificationQueue.executeNext();
  24376. }
  24377. if (this._engine.isDeterministicLockStep()) {
  24378. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24379. var defaultFPS = (60.0 / 1000.0);
  24380. var defaultFrameTime = 1000 / 60; // frame time in MS
  24381. if (this._physicsEngine) {
  24382. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24383. }
  24384. var stepsTaken = 0;
  24385. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24386. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24387. internalSteps = Math.min(internalSteps, maxSubSteps);
  24388. do {
  24389. this.onBeforeStepObservable.notifyObservers(this);
  24390. // Animations
  24391. this._animationRatio = defaultFrameTime * defaultFPS;
  24392. this._animate();
  24393. this.onAfterAnimationsObservable.notifyObservers(this);
  24394. // Physics
  24395. if (this._physicsEngine) {
  24396. this.onBeforePhysicsObservable.notifyObservers(this);
  24397. this._physicsEngine._step(defaultFrameTime / 1000);
  24398. this.onAfterPhysicsObservable.notifyObservers(this);
  24399. }
  24400. this.onAfterStepObservable.notifyObservers(this);
  24401. this._currentStepId++;
  24402. stepsTaken++;
  24403. deltaTime -= defaultFrameTime;
  24404. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24405. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24406. }
  24407. else {
  24408. // Animations
  24409. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24410. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24411. this._animate();
  24412. this.onAfterAnimationsObservable.notifyObservers(this);
  24413. // Physics
  24414. if (this._physicsEngine) {
  24415. this.onBeforePhysicsObservable.notifyObservers(this);
  24416. this._physicsEngine._step(deltaTime / 1000.0);
  24417. this.onAfterPhysicsObservable.notifyObservers(this);
  24418. }
  24419. }
  24420. // update gamepad manager
  24421. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24422. this._gamepadManager._checkGamepadsStatus();
  24423. }
  24424. // Update Cameras
  24425. if (this.activeCameras.length > 0) {
  24426. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24427. var camera = this.activeCameras[cameraIndex];
  24428. camera.update();
  24429. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24430. // rig cameras
  24431. for (var index = 0; index < camera._rigCameras.length; index++) {
  24432. camera._rigCameras[index].update();
  24433. }
  24434. }
  24435. }
  24436. }
  24437. else if (this.activeCamera) {
  24438. this.activeCamera.update();
  24439. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24440. // rig cameras
  24441. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24442. this.activeCamera._rigCameras[index].update();
  24443. }
  24444. }
  24445. }
  24446. // Before render
  24447. this.onBeforeRenderObservable.notifyObservers(this);
  24448. // Customs render targets
  24449. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24450. var engine = this.getEngine();
  24451. var currentActiveCamera = this.activeCamera;
  24452. if (this.renderTargetsEnabled) {
  24453. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24454. this._intermediateRendering = true;
  24455. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24456. var renderTarget = this.customRenderTargets[customIndex];
  24457. if (renderTarget._shouldRender()) {
  24458. this._renderId++;
  24459. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24460. if (!this.activeCamera)
  24461. throw new Error("Active camera not set");
  24462. // Viewport
  24463. engine.setViewport(this.activeCamera.viewport);
  24464. // Camera
  24465. this.updateTransformMatrix();
  24466. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24467. }
  24468. }
  24469. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24470. this._intermediateRendering = false;
  24471. this._renderId++;
  24472. }
  24473. // Restore back buffer
  24474. if (this.customRenderTargets.length > 0) {
  24475. engine.restoreDefaultFramebuffer();
  24476. }
  24477. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24478. this.activeCamera = currentActiveCamera;
  24479. // Procedural textures
  24480. if (this.proceduralTexturesEnabled) {
  24481. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24482. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24483. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24484. if (proceduralTexture._shouldRender()) {
  24485. proceduralTexture.render();
  24486. }
  24487. }
  24488. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24489. }
  24490. // Clear
  24491. if (this.autoClearDepthAndStencil || this.autoClear) {
  24492. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24493. }
  24494. // Shadows
  24495. if (this.shadowsEnabled) {
  24496. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24497. var light = this.lights[lightIndex];
  24498. var shadowGenerator = light.getShadowGenerator();
  24499. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24500. var shadowMap = (shadowGenerator.getShadowMap());
  24501. if (this.textures.indexOf(shadowMap) !== -1) {
  24502. this._renderTargets.push(shadowMap);
  24503. }
  24504. }
  24505. }
  24506. }
  24507. // Depth renderer
  24508. for (var key in this._depthRenderer) {
  24509. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24510. }
  24511. // Geometry renderer
  24512. if (this._geometryBufferRenderer) {
  24513. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24514. }
  24515. // RenderPipeline
  24516. if (this._postProcessRenderPipelineManager) {
  24517. this._postProcessRenderPipelineManager.update();
  24518. }
  24519. // Multi-cameras?
  24520. if (this.activeCameras.length > 0) {
  24521. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24522. if (cameraIndex > 0) {
  24523. this._engine.clear(null, false, true, true);
  24524. }
  24525. this._processSubCameras(this.activeCameras[cameraIndex]);
  24526. }
  24527. }
  24528. else {
  24529. if (!this.activeCamera) {
  24530. throw new Error("No camera defined");
  24531. }
  24532. this._processSubCameras(this.activeCamera);
  24533. }
  24534. // Intersection checks
  24535. this._checkIntersections();
  24536. // Update the audio listener attached to the camera
  24537. if (BABYLON.AudioEngine) {
  24538. this._updateAudioParameters();
  24539. }
  24540. // After render
  24541. if (this.afterRender) {
  24542. this.afterRender();
  24543. }
  24544. this.onAfterRenderObservable.notifyObservers(this);
  24545. // Cleaning
  24546. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24547. var data = this._toBeDisposed.data[index];
  24548. if (data) {
  24549. data.dispose();
  24550. }
  24551. this._toBeDisposed[index] = null;
  24552. }
  24553. this._toBeDisposed.reset();
  24554. if (this.dumpNextRenderTargets) {
  24555. this.dumpNextRenderTargets = false;
  24556. }
  24557. this._activeBones.addCount(0, true);
  24558. this._activeIndices.addCount(0, true);
  24559. this._activeParticles.addCount(0, true);
  24560. };
  24561. Scene.prototype._updateAudioParameters = function () {
  24562. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24563. return;
  24564. }
  24565. var listeningCamera;
  24566. var audioEngine = BABYLON.Engine.audioEngine;
  24567. if (this.activeCameras.length > 0) {
  24568. listeningCamera = this.activeCameras[0];
  24569. }
  24570. else {
  24571. listeningCamera = this.activeCamera;
  24572. }
  24573. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24574. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24575. // for VR cameras
  24576. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24577. listeningCamera = listeningCamera.rigCameras[0];
  24578. }
  24579. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24580. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24581. cameraDirection.normalize();
  24582. // To avoid some errors on GearVR
  24583. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24584. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24585. }
  24586. var i;
  24587. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24588. var sound = this.mainSoundTrack.soundCollection[i];
  24589. if (sound.useCustomAttenuation) {
  24590. sound.updateDistanceFromListener();
  24591. }
  24592. }
  24593. for (i = 0; i < this.soundTracks.length; i++) {
  24594. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24595. sound = this.soundTracks[i].soundCollection[j];
  24596. if (sound.useCustomAttenuation) {
  24597. sound.updateDistanceFromListener();
  24598. }
  24599. }
  24600. }
  24601. }
  24602. };
  24603. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24604. // Audio
  24605. get: function () {
  24606. return this._audioEnabled;
  24607. },
  24608. set: function (value) {
  24609. this._audioEnabled = value;
  24610. if (BABYLON.AudioEngine) {
  24611. if (this._audioEnabled) {
  24612. this._enableAudio();
  24613. }
  24614. else {
  24615. this._disableAudio();
  24616. }
  24617. }
  24618. },
  24619. enumerable: true,
  24620. configurable: true
  24621. });
  24622. Scene.prototype._disableAudio = function () {
  24623. var i;
  24624. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24625. this.mainSoundTrack.soundCollection[i].pause();
  24626. }
  24627. for (i = 0; i < this.soundTracks.length; i++) {
  24628. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24629. this.soundTracks[i].soundCollection[j].pause();
  24630. }
  24631. }
  24632. };
  24633. Scene.prototype._enableAudio = function () {
  24634. var i;
  24635. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24636. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24637. this.mainSoundTrack.soundCollection[i].play();
  24638. }
  24639. }
  24640. for (i = 0; i < this.soundTracks.length; i++) {
  24641. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24642. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24643. this.soundTracks[i].soundCollection[j].play();
  24644. }
  24645. }
  24646. }
  24647. };
  24648. Object.defineProperty(Scene.prototype, "headphone", {
  24649. get: function () {
  24650. return this._headphone;
  24651. },
  24652. set: function (value) {
  24653. this._headphone = value;
  24654. if (BABYLON.AudioEngine) {
  24655. if (this._headphone) {
  24656. this._switchAudioModeForHeadphones();
  24657. }
  24658. else {
  24659. this._switchAudioModeForNormalSpeakers();
  24660. }
  24661. }
  24662. },
  24663. enumerable: true,
  24664. configurable: true
  24665. });
  24666. Scene.prototype._switchAudioModeForHeadphones = function () {
  24667. this.mainSoundTrack.switchPanningModelToHRTF();
  24668. for (var i = 0; i < this.soundTracks.length; i++) {
  24669. this.soundTracks[i].switchPanningModelToHRTF();
  24670. }
  24671. };
  24672. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24673. this.mainSoundTrack.switchPanningModelToEqualPower();
  24674. for (var i = 0; i < this.soundTracks.length; i++) {
  24675. this.soundTracks[i].switchPanningModelToEqualPower();
  24676. }
  24677. };
  24678. /**
  24679. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24680. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24681. * @returns the created depth renderer
  24682. */
  24683. Scene.prototype.enableDepthRenderer = function (camera) {
  24684. camera = camera || this.activeCamera;
  24685. if (!camera) {
  24686. throw "No camera available to enable depth renderer";
  24687. }
  24688. if (!this._depthRenderer[camera.id]) {
  24689. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24690. }
  24691. return this._depthRenderer[camera.id];
  24692. };
  24693. /**
  24694. * Disables a depth renderer for a given camera
  24695. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24696. */
  24697. Scene.prototype.disableDepthRenderer = function (camera) {
  24698. camera = camera || this.activeCamera;
  24699. if (!camera || !this._depthRenderer[camera.id]) {
  24700. return;
  24701. }
  24702. this._depthRenderer[camera.id].dispose();
  24703. delete this._depthRenderer[camera.id];
  24704. };
  24705. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24706. if (ratio === void 0) { ratio = 1; }
  24707. if (this._geometryBufferRenderer) {
  24708. return this._geometryBufferRenderer;
  24709. }
  24710. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24711. if (!this._geometryBufferRenderer.isSupported) {
  24712. this._geometryBufferRenderer = null;
  24713. }
  24714. return this._geometryBufferRenderer;
  24715. };
  24716. Scene.prototype.disableGeometryBufferRenderer = function () {
  24717. if (!this._geometryBufferRenderer) {
  24718. return;
  24719. }
  24720. this._geometryBufferRenderer.dispose();
  24721. this._geometryBufferRenderer = null;
  24722. };
  24723. Scene.prototype.freezeMaterials = function () {
  24724. for (var i = 0; i < this.materials.length; i++) {
  24725. this.materials[i].freeze();
  24726. }
  24727. };
  24728. Scene.prototype.unfreezeMaterials = function () {
  24729. for (var i = 0; i < this.materials.length; i++) {
  24730. this.materials[i].unfreeze();
  24731. }
  24732. };
  24733. Scene.prototype.dispose = function () {
  24734. this.beforeRender = null;
  24735. this.afterRender = null;
  24736. this.skeletons = [];
  24737. this.morphTargetManagers = [];
  24738. this.importedMeshesFiles = new Array();
  24739. this.stopAllAnimations();
  24740. this.resetCachedMaterial();
  24741. for (var key in this._depthRenderer) {
  24742. this._depthRenderer[key].dispose();
  24743. }
  24744. if (this._gamepadManager) {
  24745. this._gamepadManager.dispose();
  24746. this._gamepadManager = null;
  24747. }
  24748. // Smart arrays
  24749. if (this.activeCamera) {
  24750. this.activeCamera._activeMeshes.dispose();
  24751. this.activeCamera = null;
  24752. }
  24753. this._activeMeshes.dispose();
  24754. this._renderingManager.dispose();
  24755. this._processedMaterials.dispose();
  24756. this._activeParticleSystems.dispose();
  24757. this._activeSkeletons.dispose();
  24758. this._softwareSkinnedMeshes.dispose();
  24759. this._renderTargets.dispose();
  24760. if (this._boundingBoxRenderer) {
  24761. this._boundingBoxRenderer.dispose();
  24762. }
  24763. this._meshesForIntersections.dispose();
  24764. this._toBeDisposed.dispose();
  24765. // Abort active requests
  24766. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24767. var request = _a[_i];
  24768. request.abort();
  24769. }
  24770. // Debug layer
  24771. if (this._debugLayer) {
  24772. this._debugLayer.hide();
  24773. }
  24774. // Events
  24775. this.onDisposeObservable.notifyObservers(this);
  24776. this.onDisposeObservable.clear();
  24777. this.onBeforeRenderObservable.clear();
  24778. this.onAfterRenderObservable.clear();
  24779. this.OnBeforeRenderTargetsRenderObservable.clear();
  24780. this.OnAfterRenderTargetsRenderObservable.clear();
  24781. this.onAfterStepObservable.clear();
  24782. this.onBeforeStepObservable.clear();
  24783. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24784. this.onAfterActiveMeshesEvaluationObservable.clear();
  24785. this.onBeforeParticlesRenderingObservable.clear();
  24786. this.onAfterParticlesRenderingObservable.clear();
  24787. this.onBeforeSpritesRenderingObservable.clear();
  24788. this.onAfterSpritesRenderingObservable.clear();
  24789. this.onBeforeDrawPhaseObservable.clear();
  24790. this.onAfterDrawPhaseObservable.clear();
  24791. this.onBeforePhysicsObservable.clear();
  24792. this.onAfterPhysicsObservable.clear();
  24793. this.onBeforeAnimationsObservable.clear();
  24794. this.onAfterAnimationsObservable.clear();
  24795. this.onDataLoadedObservable.clear();
  24796. this.detachControl();
  24797. // Release sounds & sounds tracks
  24798. if (BABYLON.AudioEngine) {
  24799. this.disposeSounds();
  24800. }
  24801. // VR Helper
  24802. if (this.VRHelper) {
  24803. this.VRHelper.dispose();
  24804. }
  24805. // Detach cameras
  24806. var canvas = this._engine.getRenderingCanvas();
  24807. if (canvas) {
  24808. var index;
  24809. for (index = 0; index < this.cameras.length; index++) {
  24810. this.cameras[index].detachControl(canvas);
  24811. }
  24812. }
  24813. // Release animation groups
  24814. while (this.animationGroups.length) {
  24815. this.animationGroups[0].dispose();
  24816. }
  24817. // Release lights
  24818. while (this.lights.length) {
  24819. this.lights[0].dispose();
  24820. }
  24821. // Release meshes
  24822. while (this.meshes.length) {
  24823. this.meshes[0].dispose(true);
  24824. }
  24825. while (this.transformNodes.length) {
  24826. this.removeTransformNode(this.transformNodes[0]);
  24827. }
  24828. // Release cameras
  24829. while (this.cameras.length) {
  24830. this.cameras[0].dispose();
  24831. }
  24832. // Release materials
  24833. if (this.defaultMaterial) {
  24834. this.defaultMaterial.dispose();
  24835. }
  24836. while (this.multiMaterials.length) {
  24837. this.multiMaterials[0].dispose();
  24838. }
  24839. while (this.materials.length) {
  24840. this.materials[0].dispose();
  24841. }
  24842. // Release particles
  24843. while (this.particleSystems.length) {
  24844. this.particleSystems[0].dispose();
  24845. }
  24846. // Release sprites
  24847. while (this.spriteManagers.length) {
  24848. this.spriteManagers[0].dispose();
  24849. }
  24850. // Release postProcesses
  24851. while (this.postProcesses.length) {
  24852. this.postProcesses[0].dispose();
  24853. }
  24854. // Release layers
  24855. while (this.layers.length) {
  24856. this.layers[0].dispose();
  24857. }
  24858. while (this.effectLayers.length) {
  24859. this.effectLayers[0].dispose();
  24860. }
  24861. // Release textures
  24862. while (this.textures.length) {
  24863. this.textures[0].dispose();
  24864. }
  24865. // Release UBO
  24866. this._sceneUbo.dispose();
  24867. if (this._alternateSceneUbo) {
  24868. this._alternateSceneUbo.dispose();
  24869. }
  24870. // Post-processes
  24871. this.postProcessManager.dispose();
  24872. if (this._postProcessRenderPipelineManager) {
  24873. this._postProcessRenderPipelineManager.dispose();
  24874. }
  24875. // Physics
  24876. if (this._physicsEngine) {
  24877. this.disablePhysicsEngine();
  24878. }
  24879. // Remove from engine
  24880. index = this._engine.scenes.indexOf(this);
  24881. if (index > -1) {
  24882. this._engine.scenes.splice(index, 1);
  24883. }
  24884. this._engine.wipeCaches(true);
  24885. this._isDisposed = true;
  24886. };
  24887. Object.defineProperty(Scene.prototype, "isDisposed", {
  24888. get: function () {
  24889. return this._isDisposed;
  24890. },
  24891. enumerable: true,
  24892. configurable: true
  24893. });
  24894. // Release sounds & sounds tracks
  24895. Scene.prototype.disposeSounds = function () {
  24896. if (!this._mainSoundTrack) {
  24897. return;
  24898. }
  24899. this.mainSoundTrack.dispose();
  24900. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24901. this.soundTracks[scIndex].dispose();
  24902. }
  24903. };
  24904. // Octrees
  24905. /**
  24906. * Get the world extend vectors with an optional filter
  24907. *
  24908. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24909. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24910. */
  24911. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24912. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24913. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24914. filterPredicate = filterPredicate || (function () { return true; });
  24915. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24916. mesh.computeWorldMatrix(true);
  24917. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24918. return;
  24919. }
  24920. var boundingInfo = mesh.getBoundingInfo();
  24921. var minBox = boundingInfo.boundingBox.minimumWorld;
  24922. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24923. BABYLON.Tools.CheckExtends(minBox, min, max);
  24924. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24925. });
  24926. return {
  24927. min: min,
  24928. max: max
  24929. };
  24930. };
  24931. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24932. if (maxCapacity === void 0) { maxCapacity = 64; }
  24933. if (maxDepth === void 0) { maxDepth = 2; }
  24934. if (!this._selectionOctree) {
  24935. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24936. }
  24937. var worldExtends = this.getWorldExtends();
  24938. // Update octree
  24939. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24940. return this._selectionOctree;
  24941. };
  24942. // Picking
  24943. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24944. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24945. var result = BABYLON.Ray.Zero();
  24946. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24947. return result;
  24948. };
  24949. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24950. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24951. var engine = this._engine;
  24952. if (!camera) {
  24953. if (!this.activeCamera)
  24954. throw new Error("Active camera not set");
  24955. camera = this.activeCamera;
  24956. }
  24957. var cameraViewport = camera.viewport;
  24958. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24959. // Moving coordinates to local viewport world
  24960. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24961. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24962. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24963. return this;
  24964. };
  24965. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24966. var result = BABYLON.Ray.Zero();
  24967. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24968. return result;
  24969. };
  24970. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24971. if (!BABYLON.PickingInfo) {
  24972. return this;
  24973. }
  24974. var engine = this._engine;
  24975. if (!camera) {
  24976. if (!this.activeCamera)
  24977. throw new Error("Active camera not set");
  24978. camera = this.activeCamera;
  24979. }
  24980. var cameraViewport = camera.viewport;
  24981. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24982. var identity = BABYLON.Matrix.Identity();
  24983. // Moving coordinates to local viewport world
  24984. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24985. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24986. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24987. return this;
  24988. };
  24989. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24990. if (!BABYLON.PickingInfo) {
  24991. return null;
  24992. }
  24993. var pickingInfo = null;
  24994. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24995. var mesh = this.meshes[meshIndex];
  24996. if (predicate) {
  24997. if (!predicate(mesh)) {
  24998. continue;
  24999. }
  25000. }
  25001. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25002. continue;
  25003. }
  25004. var world = mesh.getWorldMatrix();
  25005. var ray = rayFunction(world);
  25006. var result = mesh.intersects(ray, fastCheck);
  25007. if (!result || !result.hit)
  25008. continue;
  25009. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25010. continue;
  25011. pickingInfo = result;
  25012. if (fastCheck) {
  25013. break;
  25014. }
  25015. }
  25016. return pickingInfo || new BABYLON.PickingInfo();
  25017. };
  25018. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25019. if (!BABYLON.PickingInfo) {
  25020. return null;
  25021. }
  25022. var pickingInfos = new Array();
  25023. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25024. var mesh = this.meshes[meshIndex];
  25025. if (predicate) {
  25026. if (!predicate(mesh)) {
  25027. continue;
  25028. }
  25029. }
  25030. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25031. continue;
  25032. }
  25033. var world = mesh.getWorldMatrix();
  25034. var ray = rayFunction(world);
  25035. var result = mesh.intersects(ray, false);
  25036. if (!result || !result.hit)
  25037. continue;
  25038. pickingInfos.push(result);
  25039. }
  25040. return pickingInfos;
  25041. };
  25042. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25043. if (!BABYLON.PickingInfo) {
  25044. return null;
  25045. }
  25046. var pickingInfo = null;
  25047. if (!camera) {
  25048. if (!this.activeCamera) {
  25049. return null;
  25050. }
  25051. camera = this.activeCamera;
  25052. }
  25053. if (this.spriteManagers.length > 0) {
  25054. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25055. var spriteManager = this.spriteManagers[spriteIndex];
  25056. if (!spriteManager.isPickable) {
  25057. continue;
  25058. }
  25059. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25060. if (!result || !result.hit)
  25061. continue;
  25062. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25063. continue;
  25064. pickingInfo = result;
  25065. if (fastCheck) {
  25066. break;
  25067. }
  25068. }
  25069. }
  25070. return pickingInfo || new BABYLON.PickingInfo();
  25071. };
  25072. /** Launch a ray to try to pick a mesh in the scene
  25073. * @param x position on screen
  25074. * @param y position on screen
  25075. * @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
  25076. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25077. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25078. */
  25079. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25080. var _this = this;
  25081. if (!BABYLON.PickingInfo) {
  25082. return null;
  25083. }
  25084. return this._internalPick(function (world) {
  25085. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25086. return _this._tempPickingRay;
  25087. }, predicate, fastCheck);
  25088. };
  25089. /** Launch a ray to try to pick a sprite in the scene
  25090. * @param x position on screen
  25091. * @param y position on screen
  25092. * @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
  25093. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25094. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25095. */
  25096. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25097. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25098. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25099. };
  25100. /** Use the given ray to pick a mesh in the scene
  25101. * @param ray The ray to use to pick meshes
  25102. * @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
  25103. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25104. */
  25105. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25106. var _this = this;
  25107. return this._internalPick(function (world) {
  25108. if (!_this._pickWithRayInverseMatrix) {
  25109. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25110. }
  25111. world.invertToRef(_this._pickWithRayInverseMatrix);
  25112. if (!_this._cachedRayForTransform) {
  25113. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25114. }
  25115. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25116. return _this._cachedRayForTransform;
  25117. }, predicate, fastCheck);
  25118. };
  25119. /**
  25120. * Launch a ray to try to pick a mesh in the scene
  25121. * @param x X position on screen
  25122. * @param y Y position on screen
  25123. * @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
  25124. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25125. */
  25126. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25127. var _this = this;
  25128. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25129. };
  25130. /**
  25131. * Launch a ray to try to pick a mesh in the scene
  25132. * @param ray Ray to use
  25133. * @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
  25134. */
  25135. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25136. var _this = this;
  25137. return this._internalMultiPick(function (world) {
  25138. if (!_this._pickWithRayInverseMatrix) {
  25139. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25140. }
  25141. world.invertToRef(_this._pickWithRayInverseMatrix);
  25142. if (!_this._cachedRayForTransform) {
  25143. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25144. }
  25145. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25146. return _this._cachedRayForTransform;
  25147. }, predicate);
  25148. };
  25149. Scene.prototype.setPointerOverMesh = function (mesh) {
  25150. if (this._pointerOverMesh === mesh) {
  25151. return;
  25152. }
  25153. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25154. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25155. }
  25156. this._pointerOverMesh = mesh;
  25157. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25158. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25159. }
  25160. };
  25161. Scene.prototype.getPointerOverMesh = function () {
  25162. return this._pointerOverMesh;
  25163. };
  25164. Scene.prototype.setPointerOverSprite = function (sprite) {
  25165. if (this._pointerOverSprite === sprite) {
  25166. return;
  25167. }
  25168. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25169. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25170. }
  25171. this._pointerOverSprite = sprite;
  25172. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25173. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25174. }
  25175. };
  25176. Scene.prototype.getPointerOverSprite = function () {
  25177. return this._pointerOverSprite;
  25178. };
  25179. // Physics
  25180. Scene.prototype.getPhysicsEngine = function () {
  25181. return this._physicsEngine;
  25182. };
  25183. /**
  25184. * Enables physics to the current scene
  25185. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25186. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25187. * @return {boolean} was the physics engine initialized
  25188. */
  25189. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25190. if (gravity === void 0) { gravity = null; }
  25191. if (this._physicsEngine) {
  25192. return true;
  25193. }
  25194. try {
  25195. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25196. return true;
  25197. }
  25198. catch (e) {
  25199. BABYLON.Tools.Error(e.message);
  25200. return false;
  25201. }
  25202. };
  25203. Scene.prototype.disablePhysicsEngine = function () {
  25204. if (!this._physicsEngine) {
  25205. return;
  25206. }
  25207. this._physicsEngine.dispose();
  25208. this._physicsEngine = null;
  25209. };
  25210. Scene.prototype.isPhysicsEnabled = function () {
  25211. return this._physicsEngine !== undefined;
  25212. };
  25213. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25214. var mesh = compound.parts[0].mesh;
  25215. if (mesh.physicsImpostor) {
  25216. mesh.physicsImpostor.dispose();
  25217. mesh.physicsImpostor = null;
  25218. }
  25219. };
  25220. // Misc.
  25221. Scene.prototype._rebuildGeometries = function () {
  25222. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25223. var geometry = _a[_i];
  25224. geometry._rebuild();
  25225. }
  25226. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25227. var mesh = _c[_b];
  25228. mesh._rebuild();
  25229. }
  25230. if (this.postProcessManager) {
  25231. this.postProcessManager._rebuild();
  25232. }
  25233. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25234. var layer = _e[_d];
  25235. layer._rebuild();
  25236. }
  25237. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25238. var effectLayer = _g[_f];
  25239. effectLayer._rebuild();
  25240. }
  25241. if (this._boundingBoxRenderer) {
  25242. this._boundingBoxRenderer._rebuild();
  25243. }
  25244. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25245. var system = _j[_h];
  25246. system.rebuild();
  25247. }
  25248. if (this._postProcessRenderPipelineManager) {
  25249. this._postProcessRenderPipelineManager._rebuild();
  25250. }
  25251. };
  25252. Scene.prototype._rebuildTextures = function () {
  25253. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25254. var texture = _a[_i];
  25255. texture._rebuild();
  25256. }
  25257. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25258. };
  25259. /**
  25260. * Creates a default light for the scene.
  25261. * @param replace Whether to replace the existing lights in the scene.
  25262. */
  25263. Scene.prototype.createDefaultLight = function (replace) {
  25264. if (replace === void 0) { replace = false; }
  25265. // Dispose existing light in replace mode.
  25266. if (replace) {
  25267. if (this.lights) {
  25268. for (var i = 0; i < this.lights.length; i++) {
  25269. this.lights[i].dispose();
  25270. }
  25271. }
  25272. }
  25273. // Light
  25274. if (this.lights.length === 0) {
  25275. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25276. }
  25277. };
  25278. /**
  25279. * Creates a default camera for the scene.
  25280. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25281. * @param replace Whether to replace the existing active camera in the scene.
  25282. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25283. */
  25284. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25285. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25286. if (replace === void 0) { replace = false; }
  25287. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25288. // Dispose existing camera in replace mode.
  25289. if (replace) {
  25290. if (this.activeCamera) {
  25291. this.activeCamera.dispose();
  25292. this.activeCamera = null;
  25293. }
  25294. }
  25295. // Camera
  25296. if (!this.activeCamera) {
  25297. var worldExtends = this.getWorldExtends();
  25298. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25299. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25300. var camera;
  25301. var radius = worldSize.length() * 1.5;
  25302. // empty scene scenario!
  25303. if (!isFinite(radius)) {
  25304. radius = 1;
  25305. worldCenter.copyFromFloats(0, 0, 0);
  25306. }
  25307. if (createArcRotateCamera) {
  25308. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25309. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25310. arcRotateCamera.wheelPrecision = 100 / radius;
  25311. camera = arcRotateCamera;
  25312. }
  25313. else {
  25314. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25315. freeCamera.setTarget(worldCenter);
  25316. camera = freeCamera;
  25317. }
  25318. camera.minZ = radius * 0.01;
  25319. camera.maxZ = radius * 1000;
  25320. camera.speed = radius * 0.2;
  25321. this.activeCamera = camera;
  25322. var canvas = this.getEngine().getRenderingCanvas();
  25323. if (attachCameraControls && canvas) {
  25324. camera.attachControl(canvas);
  25325. }
  25326. }
  25327. };
  25328. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25329. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25330. if (replace === void 0) { replace = false; }
  25331. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25332. this.createDefaultLight(replace);
  25333. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25334. };
  25335. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25336. if (pbr === void 0) { pbr = false; }
  25337. if (scale === void 0) { scale = 1000; }
  25338. if (blur === void 0) { blur = 0; }
  25339. if (environmentTexture) {
  25340. this.environmentTexture = environmentTexture;
  25341. }
  25342. if (!this.environmentTexture) {
  25343. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25344. return null;
  25345. }
  25346. // Skybox
  25347. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25348. if (pbr) {
  25349. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25350. hdrSkyboxMaterial.backFaceCulling = false;
  25351. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25352. if (hdrSkyboxMaterial.reflectionTexture) {
  25353. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25354. }
  25355. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25356. hdrSkyboxMaterial.disableLighting = true;
  25357. hdrSkyboxMaterial.twoSidedLighting = true;
  25358. hdrSkybox.infiniteDistance = true;
  25359. hdrSkybox.material = hdrSkyboxMaterial;
  25360. }
  25361. else {
  25362. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25363. skyboxMaterial.backFaceCulling = false;
  25364. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25365. if (skyboxMaterial.reflectionTexture) {
  25366. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25367. }
  25368. skyboxMaterial.disableLighting = true;
  25369. hdrSkybox.infiniteDistance = true;
  25370. hdrSkybox.material = skyboxMaterial;
  25371. }
  25372. return hdrSkybox;
  25373. };
  25374. Scene.prototype.createDefaultEnvironment = function (options) {
  25375. if (BABYLON.EnvironmentHelper) {
  25376. return new BABYLON.EnvironmentHelper(options, this);
  25377. }
  25378. return null;
  25379. };
  25380. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25381. if (webVROptions === void 0) { webVROptions = {}; }
  25382. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25383. };
  25384. // Tags
  25385. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25386. if (tagsQuery === undefined) {
  25387. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25388. return list;
  25389. }
  25390. var listByTags = [];
  25391. forEach = forEach || (function (item) { return; });
  25392. for (var i in list) {
  25393. var item = list[i];
  25394. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25395. listByTags.push(item);
  25396. forEach(item);
  25397. }
  25398. }
  25399. return listByTags;
  25400. };
  25401. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25402. return this._getByTags(this.meshes, tagsQuery, forEach);
  25403. };
  25404. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25405. return this._getByTags(this.cameras, tagsQuery, forEach);
  25406. };
  25407. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25408. return this._getByTags(this.lights, tagsQuery, forEach);
  25409. };
  25410. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25411. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25412. };
  25413. /**
  25414. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25415. * This allowed control for front to back rendering or reversly depending of the special needs.
  25416. *
  25417. * @param renderingGroupId The rendering group id corresponding to its index
  25418. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25419. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25420. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25421. */
  25422. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25423. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25424. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25425. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25426. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25427. };
  25428. /**
  25429. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25430. *
  25431. * @param renderingGroupId The rendering group id corresponding to its index
  25432. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25433. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25434. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25435. */
  25436. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25437. if (depth === void 0) { depth = true; }
  25438. if (stencil === void 0) { stencil = true; }
  25439. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25440. };
  25441. /**
  25442. * Will flag all materials as dirty to trigger new shader compilation
  25443. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25444. */
  25445. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25446. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25447. var material = _a[_i];
  25448. if (predicate && !predicate(material)) {
  25449. continue;
  25450. }
  25451. material.markAsDirty(flag);
  25452. }
  25453. };
  25454. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25455. var _this = this;
  25456. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25457. this._activeRequests.push(request);
  25458. request.onCompleteObservable.add(function (request) {
  25459. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25460. });
  25461. return request;
  25462. };
  25463. /** @ignore */
  25464. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25465. var _this = this;
  25466. return new Promise(function (resolve, reject) {
  25467. _this._loadFile(url, function (data) {
  25468. resolve(data);
  25469. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25470. reject(exception);
  25471. });
  25472. });
  25473. };
  25474. // Statics
  25475. Scene._FOGMODE_NONE = 0;
  25476. Scene._FOGMODE_EXP = 1;
  25477. Scene._FOGMODE_EXP2 = 2;
  25478. Scene._FOGMODE_LINEAR = 3;
  25479. Scene._uniqueIdCounter = 0;
  25480. Scene.MinDeltaTime = 1.0;
  25481. Scene.MaxDeltaTime = 1000.0;
  25482. /** The distance in pixel that you have to move to prevent some events */
  25483. Scene.DragMovementThreshold = 10; // in pixels
  25484. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25485. Scene.LongPressDelay = 500; // in milliseconds
  25486. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25487. Scene.DoubleClickDelay = 300; // in milliseconds
  25488. /** If you need to check double click without raising a single click at first click, enable this flag */
  25489. Scene.ExclusiveDoubleClickMode = false;
  25490. return Scene;
  25491. }());
  25492. BABYLON.Scene = Scene;
  25493. })(BABYLON || (BABYLON = {}));
  25494. //# sourceMappingURL=babylon.scene.js.map
  25495. var BABYLON;
  25496. (function (BABYLON) {
  25497. /**
  25498. * Set of assets to keep when moving a scene into an asset container.
  25499. */
  25500. var KeepAssets = /** @class */ (function () {
  25501. function KeepAssets() {
  25502. /**
  25503. * Cameras to keep.
  25504. */
  25505. this.cameras = new Array();
  25506. /**
  25507. * Lights to keep.
  25508. */
  25509. this.lights = new Array();
  25510. /**
  25511. * Meshes to keep.
  25512. */
  25513. this.meshes = new Array();
  25514. /**
  25515. * Skeletons to keep.
  25516. */
  25517. this.skeletons = new Array();
  25518. /**
  25519. * ParticleSystems to keep.
  25520. */
  25521. this.particleSystems = new Array();
  25522. /**
  25523. * Animations to keep.
  25524. */
  25525. this.animations = new Array();
  25526. /**
  25527. * MultiMaterials to keep.
  25528. */
  25529. this.multiMaterials = new Array();
  25530. /**
  25531. * Materials to keep.
  25532. */
  25533. this.materials = new Array();
  25534. /**
  25535. * MorphTargetManagers to keep.
  25536. */
  25537. this.morphTargetManagers = new Array();
  25538. /**
  25539. * Geometries to keep.
  25540. */
  25541. this.geometries = new Array();
  25542. /**
  25543. * TransformNodes to keep.
  25544. */
  25545. this.transformNodes = new Array();
  25546. /**
  25547. * LensFlareSystems to keep.
  25548. */
  25549. this.lensFlareSystems = new Array();
  25550. /**
  25551. * ShadowGenerators to keep.
  25552. */
  25553. this.shadowGenerators = new Array();
  25554. /**
  25555. * ActionManagers to keep.
  25556. */
  25557. this.actionManagers = new Array();
  25558. /**
  25559. * Sounds to keep.
  25560. */
  25561. this.sounds = new Array();
  25562. }
  25563. return KeepAssets;
  25564. }());
  25565. BABYLON.KeepAssets = KeepAssets;
  25566. /**
  25567. * Container with a set of assets that can be added or removed from a scene.
  25568. */
  25569. var AssetContainer = /** @class */ (function () {
  25570. /**
  25571. * Instantiates an AssetContainer.
  25572. * @param scene The scene the AssetContainer belongs to.
  25573. */
  25574. function AssetContainer(scene) {
  25575. // Objects
  25576. /**
  25577. * Cameras populated in the container.
  25578. */
  25579. this.cameras = new Array();
  25580. /**
  25581. * Lights populated in the container.
  25582. */
  25583. this.lights = new Array();
  25584. /**
  25585. * Meshes populated in the container.
  25586. */
  25587. this.meshes = new Array();
  25588. /**
  25589. * Skeletons populated in the container.
  25590. */
  25591. this.skeletons = new Array();
  25592. /**
  25593. * ParticleSystems populated in the container.
  25594. */
  25595. this.particleSystems = new Array();
  25596. /**
  25597. * Animations populated in the container.
  25598. */
  25599. this.animations = new Array();
  25600. /**
  25601. * MultiMaterials populated in the container.
  25602. */
  25603. this.multiMaterials = new Array();
  25604. /**
  25605. * Materials populated in the container.
  25606. */
  25607. this.materials = new Array();
  25608. /**
  25609. * MorphTargetManagers populated in the container.
  25610. */
  25611. this.morphTargetManagers = new Array();
  25612. /**
  25613. * Geometries populated in the container.
  25614. */
  25615. this.geometries = new Array();
  25616. /**
  25617. * TransformNodes populated in the container.
  25618. */
  25619. this.transformNodes = new Array();
  25620. /**
  25621. * LensFlareSystems populated in the container.
  25622. */
  25623. this.lensFlareSystems = new Array();
  25624. /**
  25625. * ShadowGenerators populated in the container.
  25626. */
  25627. this.shadowGenerators = new Array();
  25628. /**
  25629. * ActionManagers populated in the container.
  25630. */
  25631. this.actionManagers = new Array();
  25632. /**
  25633. * Sounds populated in the container.
  25634. */
  25635. this.sounds = new Array();
  25636. this.scene = scene;
  25637. }
  25638. /**
  25639. * Adds all the assets from the container to the scene.
  25640. */
  25641. AssetContainer.prototype.addAllToScene = function () {
  25642. var _this = this;
  25643. this.cameras.forEach(function (o) {
  25644. _this.scene.addCamera(o);
  25645. });
  25646. this.lights.forEach(function (o) {
  25647. _this.scene.addLight(o);
  25648. });
  25649. this.meshes.forEach(function (o) {
  25650. _this.scene.addMesh(o);
  25651. });
  25652. this.skeletons.forEach(function (o) {
  25653. _this.scene.addSkeleton(o);
  25654. });
  25655. this.particleSystems.forEach(function (o) {
  25656. _this.scene.addParticleSystem(o);
  25657. });
  25658. this.animations.forEach(function (o) {
  25659. _this.scene.addAnimation(o);
  25660. });
  25661. this.multiMaterials.forEach(function (o) {
  25662. _this.scene.addMultiMaterial(o);
  25663. });
  25664. this.materials.forEach(function (o) {
  25665. _this.scene.addMaterial(o);
  25666. });
  25667. this.morphTargetManagers.forEach(function (o) {
  25668. _this.scene.addMorphTargetManager(o);
  25669. });
  25670. this.geometries.forEach(function (o) {
  25671. _this.scene.addGeometry(o);
  25672. });
  25673. this.transformNodes.forEach(function (o) {
  25674. _this.scene.addTransformNode(o);
  25675. });
  25676. this.lensFlareSystems.forEach(function (o) {
  25677. _this.scene.addLensFlareSystem(o);
  25678. });
  25679. this.actionManagers.forEach(function (o) {
  25680. _this.scene.addActionManager(o);
  25681. });
  25682. this.sounds.forEach(function (o) {
  25683. o.play();
  25684. o.autoplay = true;
  25685. _this.scene.mainSoundTrack.AddSound(o);
  25686. });
  25687. };
  25688. /**
  25689. * Removes all the assets in the container from the scene
  25690. */
  25691. AssetContainer.prototype.removeAllFromScene = function () {
  25692. var _this = this;
  25693. this.cameras.forEach(function (o) {
  25694. _this.scene.removeCamera(o);
  25695. });
  25696. this.lights.forEach(function (o) {
  25697. _this.scene.removeLight(o);
  25698. });
  25699. this.meshes.forEach(function (o) {
  25700. _this.scene.removeMesh(o);
  25701. });
  25702. this.skeletons.forEach(function (o) {
  25703. _this.scene.removeSkeleton(o);
  25704. });
  25705. this.particleSystems.forEach(function (o) {
  25706. _this.scene.removeParticleSystem(o);
  25707. });
  25708. this.animations.forEach(function (o) {
  25709. _this.scene.removeAnimation(o);
  25710. });
  25711. this.multiMaterials.forEach(function (o) {
  25712. _this.scene.removeMultiMaterial(o);
  25713. });
  25714. this.materials.forEach(function (o) {
  25715. _this.scene.removeMaterial(o);
  25716. });
  25717. this.morphTargetManagers.forEach(function (o) {
  25718. _this.scene.removeMorphTargetManager(o);
  25719. });
  25720. this.geometries.forEach(function (o) {
  25721. _this.scene.removeGeometry(o);
  25722. });
  25723. this.transformNodes.forEach(function (o) {
  25724. _this.scene.removeTransformNode(o);
  25725. });
  25726. this.lensFlareSystems.forEach(function (o) {
  25727. _this.scene.removeLensFlareSystem(o);
  25728. });
  25729. this.actionManagers.forEach(function (o) {
  25730. _this.scene.removeActionManager(o);
  25731. });
  25732. this.sounds.forEach(function (o) {
  25733. o.stop();
  25734. o.autoplay = false;
  25735. _this.scene.mainSoundTrack.RemoveSound(o);
  25736. });
  25737. };
  25738. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25739. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25740. var asset = sourceAssets_1[_i];
  25741. var move = true;
  25742. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25743. var keepAsset = keepAssets_1[_a];
  25744. if (asset === keepAsset) {
  25745. move = false;
  25746. break;
  25747. }
  25748. }
  25749. if (move) {
  25750. targetAssets.push(asset);
  25751. }
  25752. }
  25753. };
  25754. /**
  25755. * Removes all the assets contained in the scene and adds them to the container.
  25756. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25757. */
  25758. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25759. if (keepAssets === undefined) {
  25760. keepAssets = new KeepAssets();
  25761. }
  25762. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25763. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25764. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25765. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25766. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25767. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25768. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25769. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25770. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25771. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25772. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25773. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25774. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25775. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25776. this.removeAllFromScene();
  25777. };
  25778. return AssetContainer;
  25779. }());
  25780. BABYLON.AssetContainer = AssetContainer;
  25781. })(BABYLON || (BABYLON = {}));
  25782. //# sourceMappingURL=babylon.assetContainer.js.map
  25783. var BABYLON;
  25784. (function (BABYLON) {
  25785. var Buffer = /** @class */ (function () {
  25786. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25787. if (instanced === void 0) { instanced = false; }
  25788. if (engine instanceof BABYLON.Mesh) {
  25789. this._engine = engine.getScene().getEngine();
  25790. }
  25791. else {
  25792. this._engine = engine;
  25793. }
  25794. this._updatable = updatable;
  25795. this._instanced = instanced;
  25796. this._data = data;
  25797. this._strideSize = stride;
  25798. if (!postponeInternalCreation) {
  25799. this.create();
  25800. }
  25801. }
  25802. /**
  25803. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25804. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25805. * @param offset defines offset in the buffer (0 by default)
  25806. * @param size defines the size in floats of attributes (position is 3 for instance)
  25807. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25808. * @param instanced defines if the vertex buffer contains indexed data
  25809. * @returns the new vertex buffer
  25810. */
  25811. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25812. // a lot of these parameters are ignored as they are overriden by the buffer
  25813. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25814. };
  25815. // Properties
  25816. Buffer.prototype.isUpdatable = function () {
  25817. return this._updatable;
  25818. };
  25819. Buffer.prototype.getData = function () {
  25820. return this._data;
  25821. };
  25822. Buffer.prototype.getBuffer = function () {
  25823. return this._buffer;
  25824. };
  25825. Buffer.prototype.getStrideSize = function () {
  25826. return this._strideSize;
  25827. };
  25828. // public getIsInstanced(): boolean {
  25829. // return this._instanced;
  25830. // }
  25831. // public get instanceDivisor(): number {
  25832. // return this._instanceDivisor;
  25833. // }
  25834. // public set instanceDivisor(value: number) {
  25835. // this._instanceDivisor = value;
  25836. // if (value == 0) {
  25837. // this._instanced = false;
  25838. // } else {
  25839. // this._instanced = true;
  25840. // }
  25841. // }
  25842. // Methods
  25843. Buffer.prototype.create = function (data) {
  25844. if (data === void 0) { data = null; }
  25845. if (!data && this._buffer) {
  25846. return; // nothing to do
  25847. }
  25848. data = data || this._data;
  25849. if (!data) {
  25850. return;
  25851. }
  25852. if (!this._buffer) {
  25853. if (this._updatable) {
  25854. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25855. this._data = data;
  25856. }
  25857. else {
  25858. this._buffer = this._engine.createVertexBuffer(data);
  25859. }
  25860. }
  25861. else if (this._updatable) {
  25862. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25863. this._data = data;
  25864. }
  25865. };
  25866. Buffer.prototype._rebuild = function () {
  25867. this._buffer = null;
  25868. this.create(this._data);
  25869. };
  25870. Buffer.prototype.update = function (data) {
  25871. this.create(data);
  25872. };
  25873. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25874. if (!this._buffer) {
  25875. return;
  25876. }
  25877. if (this._updatable) {
  25878. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25879. this._data = null;
  25880. }
  25881. };
  25882. Buffer.prototype.dispose = function () {
  25883. if (!this._buffer) {
  25884. return;
  25885. }
  25886. if (this._engine._releaseBuffer(this._buffer)) {
  25887. this._buffer = null;
  25888. }
  25889. };
  25890. return Buffer;
  25891. }());
  25892. BABYLON.Buffer = Buffer;
  25893. })(BABYLON || (BABYLON = {}));
  25894. //# sourceMappingURL=babylon.buffer.js.map
  25895. var BABYLON;
  25896. (function (BABYLON) {
  25897. var VertexBuffer = /** @class */ (function () {
  25898. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25899. if (data instanceof BABYLON.Buffer) {
  25900. if (!stride) {
  25901. stride = data.getStrideSize();
  25902. }
  25903. this._buffer = data;
  25904. this._ownsBuffer = false;
  25905. }
  25906. else {
  25907. if (!stride) {
  25908. stride = VertexBuffer.DeduceStride(kind);
  25909. }
  25910. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25911. this._ownsBuffer = true;
  25912. }
  25913. this._stride = stride;
  25914. this._instanced = instanced !== undefined ? instanced : false;
  25915. this._instanceDivisor = instanced ? 1 : 0;
  25916. this._offset = offset ? offset : 0;
  25917. this._size = size ? size : stride;
  25918. this._kind = kind;
  25919. }
  25920. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25921. /**
  25922. * Gets or sets the instance divisor when in instanced mode
  25923. */
  25924. get: function () {
  25925. return this._instanceDivisor;
  25926. },
  25927. set: function (value) {
  25928. this._instanceDivisor = value;
  25929. if (value == 0) {
  25930. this._instanced = false;
  25931. }
  25932. else {
  25933. this._instanced = true;
  25934. }
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. VertexBuffer.prototype._rebuild = function () {
  25940. if (!this._buffer) {
  25941. return;
  25942. }
  25943. this._buffer._rebuild();
  25944. };
  25945. /**
  25946. * Returns the kind of the VertexBuffer (string).
  25947. */
  25948. VertexBuffer.prototype.getKind = function () {
  25949. return this._kind;
  25950. };
  25951. // Properties
  25952. /**
  25953. * Boolean : is the VertexBuffer updatable ?
  25954. */
  25955. VertexBuffer.prototype.isUpdatable = function () {
  25956. return this._buffer.isUpdatable();
  25957. };
  25958. /**
  25959. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25960. */
  25961. VertexBuffer.prototype.getData = function () {
  25962. return this._buffer.getData();
  25963. };
  25964. /**
  25965. * Returns the WebGLBuffer associated to the VertexBuffer.
  25966. */
  25967. VertexBuffer.prototype.getBuffer = function () {
  25968. return this._buffer.getBuffer();
  25969. };
  25970. /**
  25971. * Returns the stride of the VertexBuffer (integer).
  25972. */
  25973. VertexBuffer.prototype.getStrideSize = function () {
  25974. return this._stride;
  25975. };
  25976. /**
  25977. * Returns the offset (integer).
  25978. */
  25979. VertexBuffer.prototype.getOffset = function () {
  25980. return this._offset;
  25981. };
  25982. /**
  25983. * Returns the VertexBuffer total size (integer).
  25984. */
  25985. VertexBuffer.prototype.getSize = function () {
  25986. return this._size;
  25987. };
  25988. /**
  25989. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25990. */
  25991. VertexBuffer.prototype.getIsInstanced = function () {
  25992. return this._instanced;
  25993. };
  25994. /**
  25995. * Returns the instancing divisor, zero for non-instanced (integer).
  25996. */
  25997. VertexBuffer.prototype.getInstanceDivisor = function () {
  25998. return this._instanceDivisor;
  25999. };
  26000. // Methods
  26001. /**
  26002. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26003. * Returns the created WebGLBuffer.
  26004. */
  26005. VertexBuffer.prototype.create = function (data) {
  26006. return this._buffer.create(data);
  26007. };
  26008. /**
  26009. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26010. * This function will create a new buffer if the current one is not updatable
  26011. * Returns the updated WebGLBuffer.
  26012. */
  26013. VertexBuffer.prototype.update = function (data) {
  26014. return this._buffer.update(data);
  26015. };
  26016. /**
  26017. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26018. * Returns the directly updated WebGLBuffer.
  26019. */
  26020. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26021. return this._buffer.updateDirectly(data, offset);
  26022. };
  26023. /**
  26024. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26025. */
  26026. VertexBuffer.prototype.dispose = function () {
  26027. if (this._ownsBuffer) {
  26028. this._buffer.dispose();
  26029. }
  26030. };
  26031. Object.defineProperty(VertexBuffer, "PositionKind", {
  26032. get: function () {
  26033. return VertexBuffer._PositionKind;
  26034. },
  26035. enumerable: true,
  26036. configurable: true
  26037. });
  26038. Object.defineProperty(VertexBuffer, "NormalKind", {
  26039. get: function () {
  26040. return VertexBuffer._NormalKind;
  26041. },
  26042. enumerable: true,
  26043. configurable: true
  26044. });
  26045. Object.defineProperty(VertexBuffer, "TangentKind", {
  26046. get: function () {
  26047. return VertexBuffer._TangentKind;
  26048. },
  26049. enumerable: true,
  26050. configurable: true
  26051. });
  26052. Object.defineProperty(VertexBuffer, "UVKind", {
  26053. get: function () {
  26054. return VertexBuffer._UVKind;
  26055. },
  26056. enumerable: true,
  26057. configurable: true
  26058. });
  26059. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26060. get: function () {
  26061. return VertexBuffer._UV2Kind;
  26062. },
  26063. enumerable: true,
  26064. configurable: true
  26065. });
  26066. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26067. get: function () {
  26068. return VertexBuffer._UV3Kind;
  26069. },
  26070. enumerable: true,
  26071. configurable: true
  26072. });
  26073. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26074. get: function () {
  26075. return VertexBuffer._UV4Kind;
  26076. },
  26077. enumerable: true,
  26078. configurable: true
  26079. });
  26080. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26081. get: function () {
  26082. return VertexBuffer._UV5Kind;
  26083. },
  26084. enumerable: true,
  26085. configurable: true
  26086. });
  26087. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26088. get: function () {
  26089. return VertexBuffer._UV6Kind;
  26090. },
  26091. enumerable: true,
  26092. configurable: true
  26093. });
  26094. Object.defineProperty(VertexBuffer, "ColorKind", {
  26095. get: function () {
  26096. return VertexBuffer._ColorKind;
  26097. },
  26098. enumerable: true,
  26099. configurable: true
  26100. });
  26101. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26102. get: function () {
  26103. return VertexBuffer._MatricesIndicesKind;
  26104. },
  26105. enumerable: true,
  26106. configurable: true
  26107. });
  26108. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26109. get: function () {
  26110. return VertexBuffer._MatricesWeightsKind;
  26111. },
  26112. enumerable: true,
  26113. configurable: true
  26114. });
  26115. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26116. get: function () {
  26117. return VertexBuffer._MatricesIndicesExtraKind;
  26118. },
  26119. enumerable: true,
  26120. configurable: true
  26121. });
  26122. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26123. get: function () {
  26124. return VertexBuffer._MatricesWeightsExtraKind;
  26125. },
  26126. enumerable: true,
  26127. configurable: true
  26128. });
  26129. /**
  26130. * Deduces the stride given a kind.
  26131. * @param kind The kind string to deduce
  26132. * @returns The deduced stride
  26133. */
  26134. VertexBuffer.DeduceStride = function (kind) {
  26135. switch (kind) {
  26136. case VertexBuffer.UVKind:
  26137. case VertexBuffer.UV2Kind:
  26138. case VertexBuffer.UV3Kind:
  26139. case VertexBuffer.UV4Kind:
  26140. case VertexBuffer.UV5Kind:
  26141. case VertexBuffer.UV6Kind:
  26142. return 2;
  26143. case VertexBuffer.NormalKind:
  26144. case VertexBuffer.PositionKind:
  26145. return 3;
  26146. case VertexBuffer.ColorKind:
  26147. case VertexBuffer.MatricesIndicesKind:
  26148. case VertexBuffer.MatricesIndicesExtraKind:
  26149. case VertexBuffer.MatricesWeightsKind:
  26150. case VertexBuffer.MatricesWeightsExtraKind:
  26151. case VertexBuffer.TangentKind:
  26152. return 4;
  26153. default:
  26154. throw new Error("Invalid kind '" + kind + "'");
  26155. }
  26156. };
  26157. // Enums
  26158. VertexBuffer._PositionKind = "position";
  26159. VertexBuffer._NormalKind = "normal";
  26160. VertexBuffer._TangentKind = "tangent";
  26161. VertexBuffer._UVKind = "uv";
  26162. VertexBuffer._UV2Kind = "uv2";
  26163. VertexBuffer._UV3Kind = "uv3";
  26164. VertexBuffer._UV4Kind = "uv4";
  26165. VertexBuffer._UV5Kind = "uv5";
  26166. VertexBuffer._UV6Kind = "uv6";
  26167. VertexBuffer._ColorKind = "color";
  26168. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26169. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26170. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26171. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26172. return VertexBuffer;
  26173. }());
  26174. BABYLON.VertexBuffer = VertexBuffer;
  26175. })(BABYLON || (BABYLON = {}));
  26176. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26177. var BABYLON;
  26178. (function (BABYLON) {
  26179. /**
  26180. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26181. */
  26182. var DummyInternalTextureTracker = /** @class */ (function () {
  26183. function DummyInternalTextureTracker() {
  26184. /**
  26185. * Gets or set the previous tracker in the list
  26186. */
  26187. this.previous = null;
  26188. /**
  26189. * Gets or set the next tracker in the list
  26190. */
  26191. this.next = null;
  26192. }
  26193. return DummyInternalTextureTracker;
  26194. }());
  26195. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26196. })(BABYLON || (BABYLON = {}));
  26197. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26198. var BABYLON;
  26199. (function (BABYLON) {
  26200. /**
  26201. * Class used to store data associated with WebGL texture data for the engine
  26202. * This class should not be used directly
  26203. */
  26204. var InternalTexture = /** @class */ (function () {
  26205. /**
  26206. * Creates a new InternalTexture
  26207. * @param engine defines the engine to use
  26208. * @param dataSource defines the type of data that will be used
  26209. */
  26210. function InternalTexture(engine, dataSource) {
  26211. /**
  26212. * Observable called when the texture is loaded
  26213. */
  26214. this.onLoadedObservable = new BABYLON.Observable();
  26215. /**
  26216. * Gets or set the previous tracker in the list
  26217. */
  26218. this.previous = null;
  26219. /**
  26220. * Gets or set the next tracker in the list
  26221. */
  26222. this.next = null;
  26223. // Private
  26224. /** @ignore */
  26225. this._initialSlot = -1;
  26226. /** @ignore */
  26227. this._designatedSlot = -1;
  26228. /** @ignore */
  26229. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26230. /** @ignore */
  26231. this._comparisonFunction = 0;
  26232. /** @ignore */
  26233. this._references = 1;
  26234. this._engine = engine;
  26235. this._dataSource = dataSource;
  26236. this._webGLTexture = engine._createTexture();
  26237. }
  26238. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26239. /**
  26240. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26241. */
  26242. get: function () {
  26243. return this._dataSource;
  26244. },
  26245. enumerable: true,
  26246. configurable: true
  26247. });
  26248. /**
  26249. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26250. */
  26251. InternalTexture.prototype.incrementReferences = function () {
  26252. this._references++;
  26253. };
  26254. /**
  26255. * Change the size of the texture (not the size of the content)
  26256. * @param width defines the new width
  26257. * @param height defines the new height
  26258. * @param depth defines the new depth (1 by default)
  26259. */
  26260. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26261. if (depth === void 0) { depth = 1; }
  26262. this.width = width;
  26263. this.height = height;
  26264. this.depth = depth;
  26265. this.baseWidth = width;
  26266. this.baseHeight = height;
  26267. this.baseDepth = depth;
  26268. this._size = width * height * depth;
  26269. };
  26270. /** @ignore */
  26271. InternalTexture.prototype._rebuild = function () {
  26272. var _this = this;
  26273. var proxy;
  26274. this.isReady = false;
  26275. this._cachedCoordinatesMode = null;
  26276. this._cachedWrapU = null;
  26277. this._cachedWrapV = null;
  26278. this._cachedAnisotropicFilteringLevel = null;
  26279. switch (this._dataSource) {
  26280. case InternalTexture.DATASOURCE_TEMP:
  26281. return;
  26282. case InternalTexture.DATASOURCE_URL:
  26283. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26284. _this.isReady = true;
  26285. }, null, this._buffer, undefined, this.format);
  26286. proxy._swapAndDie(this);
  26287. return;
  26288. case InternalTexture.DATASOURCE_RAW:
  26289. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26290. proxy._swapAndDie(this);
  26291. this.isReady = true;
  26292. return;
  26293. case InternalTexture.DATASOURCE_RAW3D:
  26294. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26295. proxy._swapAndDie(this);
  26296. this.isReady = true;
  26297. return;
  26298. case InternalTexture.DATASOURCE_DYNAMIC:
  26299. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26300. proxy._swapAndDie(this);
  26301. // The engine will make sure to update content so no need to flag it as isReady = true
  26302. return;
  26303. case InternalTexture.DATASOURCE_RENDERTARGET:
  26304. var options = new BABYLON.RenderTargetCreationOptions();
  26305. options.generateDepthBuffer = this._generateDepthBuffer;
  26306. options.generateMipMaps = this.generateMipMaps;
  26307. options.generateStencilBuffer = this._generateStencilBuffer;
  26308. options.samplingMode = this.samplingMode;
  26309. options.type = this.type;
  26310. if (this.isCube) {
  26311. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26312. }
  26313. else {
  26314. var size = {
  26315. width: this.width,
  26316. height: this.height
  26317. };
  26318. proxy = this._engine.createRenderTargetTexture(size, options);
  26319. }
  26320. proxy._swapAndDie(this);
  26321. this.isReady = true;
  26322. return;
  26323. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26324. var depthTextureOptions = {
  26325. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26326. comparisonFunction: this._comparisonFunction,
  26327. generateStencil: this._generateStencilBuffer,
  26328. };
  26329. if (this.isCube) {
  26330. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26331. }
  26332. else {
  26333. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26334. }
  26335. proxy._swapAndDie(this);
  26336. this.isReady = true;
  26337. return;
  26338. case InternalTexture.DATASOURCE_CUBE:
  26339. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26340. _this.isReady = true;
  26341. }, null, this.format, this._extension);
  26342. proxy._swapAndDie(this);
  26343. return;
  26344. case InternalTexture.DATASOURCE_CUBERAW:
  26345. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26346. proxy._swapAndDie(this);
  26347. this.isReady = true;
  26348. return;
  26349. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26350. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26351. if (proxy) {
  26352. proxy._swapAndDie(_this);
  26353. }
  26354. _this.isReady = true;
  26355. }, null, this.format, this._extension);
  26356. return;
  26357. }
  26358. };
  26359. InternalTexture.prototype._swapAndDie = function (target) {
  26360. target._webGLTexture = this._webGLTexture;
  26361. if (this._framebuffer) {
  26362. target._framebuffer = this._framebuffer;
  26363. }
  26364. if (this._depthStencilBuffer) {
  26365. target._depthStencilBuffer = this._depthStencilBuffer;
  26366. }
  26367. if (this._lodTextureHigh) {
  26368. if (target._lodTextureHigh) {
  26369. target._lodTextureHigh.dispose();
  26370. }
  26371. target._lodTextureHigh = this._lodTextureHigh;
  26372. }
  26373. if (this._lodTextureMid) {
  26374. if (target._lodTextureMid) {
  26375. target._lodTextureMid.dispose();
  26376. }
  26377. target._lodTextureMid = this._lodTextureMid;
  26378. }
  26379. if (this._lodTextureLow) {
  26380. if (target._lodTextureLow) {
  26381. target._lodTextureLow.dispose();
  26382. }
  26383. target._lodTextureLow = this._lodTextureLow;
  26384. }
  26385. var cache = this._engine.getLoadedTexturesCache();
  26386. var index = cache.indexOf(this);
  26387. if (index !== -1) {
  26388. cache.splice(index, 1);
  26389. }
  26390. };
  26391. /**
  26392. * Dispose the current allocated resources
  26393. */
  26394. InternalTexture.prototype.dispose = function () {
  26395. if (!this._webGLTexture) {
  26396. return;
  26397. }
  26398. this._references--;
  26399. if (this._references === 0) {
  26400. this._engine._releaseTexture(this);
  26401. this._webGLTexture = null;
  26402. this.previous = null;
  26403. this.next = null;
  26404. }
  26405. };
  26406. /**
  26407. * The source of the texture data is unknown
  26408. */
  26409. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26410. /**
  26411. * Texture data comes from an URL
  26412. */
  26413. InternalTexture.DATASOURCE_URL = 1;
  26414. /**
  26415. * Texture data is only used for temporary storage
  26416. */
  26417. InternalTexture.DATASOURCE_TEMP = 2;
  26418. /**
  26419. * Texture data comes from raw data (ArrayBuffer)
  26420. */
  26421. InternalTexture.DATASOURCE_RAW = 3;
  26422. /**
  26423. * Texture content is dynamic (video or dynamic texture)
  26424. */
  26425. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26426. /**
  26427. * Texture content is generated by rendering to it
  26428. */
  26429. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26430. /**
  26431. * Texture content is part of a multi render target process
  26432. */
  26433. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26434. /**
  26435. * Texture data comes from a cube data file
  26436. */
  26437. InternalTexture.DATASOURCE_CUBE = 7;
  26438. /**
  26439. * Texture data comes from a raw cube data
  26440. */
  26441. InternalTexture.DATASOURCE_CUBERAW = 8;
  26442. /**
  26443. * Texture data come from a prefiltered cube data file
  26444. */
  26445. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26446. /**
  26447. * Texture content is raw 3D data
  26448. */
  26449. InternalTexture.DATASOURCE_RAW3D = 10;
  26450. /**
  26451. * Texture content is a depth texture
  26452. */
  26453. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26454. return InternalTexture;
  26455. }());
  26456. BABYLON.InternalTexture = InternalTexture;
  26457. })(BABYLON || (BABYLON = {}));
  26458. //# sourceMappingURL=babylon.internalTexture.js.map
  26459. var BABYLON;
  26460. (function (BABYLON) {
  26461. var BaseTexture = /** @class */ (function () {
  26462. function BaseTexture(scene) {
  26463. this._hasAlpha = false;
  26464. this.getAlphaFromRGB = false;
  26465. this.level = 1;
  26466. this.coordinatesIndex = 0;
  26467. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26468. /**
  26469. * | Value | Type | Description |
  26470. * | ----- | ------------------ | ----------- |
  26471. * | 0 | CLAMP_ADDRESSMODE | |
  26472. * | 1 | WRAP_ADDRESSMODE | |
  26473. * | 2 | MIRROR_ADDRESSMODE | |
  26474. */
  26475. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26476. /**
  26477. * | Value | Type | Description |
  26478. * | ----- | ------------------ | ----------- |
  26479. * | 0 | CLAMP_ADDRESSMODE | |
  26480. * | 1 | WRAP_ADDRESSMODE | |
  26481. * | 2 | MIRROR_ADDRESSMODE | |
  26482. */
  26483. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26484. /**
  26485. * | Value | Type | Description |
  26486. * | ----- | ------------------ | ----------- |
  26487. * | 0 | CLAMP_ADDRESSMODE | |
  26488. * | 1 | WRAP_ADDRESSMODE | |
  26489. * | 2 | MIRROR_ADDRESSMODE | |
  26490. */
  26491. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26492. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26493. this.isCube = false;
  26494. this.is3D = false;
  26495. this.gammaSpace = true;
  26496. this.invertZ = false;
  26497. this.lodLevelInAlpha = false;
  26498. this.lodGenerationOffset = 0.0;
  26499. this.lodGenerationScale = 0.8;
  26500. this.isRenderTarget = false;
  26501. this.animations = new Array();
  26502. /**
  26503. * An event triggered when the texture is disposed.
  26504. * @type {BABYLON.Observable}
  26505. */
  26506. this.onDisposeObservable = new BABYLON.Observable();
  26507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26508. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26509. if (this._scene) {
  26510. this._scene.textures.push(this);
  26511. }
  26512. this._uid = null;
  26513. }
  26514. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26515. get: function () {
  26516. return this._hasAlpha;
  26517. },
  26518. set: function (value) {
  26519. if (this._hasAlpha === value) {
  26520. return;
  26521. }
  26522. this._hasAlpha = value;
  26523. if (this._scene) {
  26524. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26525. }
  26526. },
  26527. enumerable: true,
  26528. configurable: true
  26529. });
  26530. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26531. get: function () {
  26532. return this._coordinatesMode;
  26533. },
  26534. /**
  26535. * How a texture is mapped.
  26536. *
  26537. * | Value | Type | Description |
  26538. * | ----- | ----------------------------------- | ----------- |
  26539. * | 0 | EXPLICIT_MODE | |
  26540. * | 1 | SPHERICAL_MODE | |
  26541. * | 2 | PLANAR_MODE | |
  26542. * | 3 | CUBIC_MODE | |
  26543. * | 4 | PROJECTION_MODE | |
  26544. * | 5 | SKYBOX_MODE | |
  26545. * | 6 | INVCUBIC_MODE | |
  26546. * | 7 | EQUIRECTANGULAR_MODE | |
  26547. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26548. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26549. */
  26550. set: function (value) {
  26551. if (this._coordinatesMode === value) {
  26552. return;
  26553. }
  26554. this._coordinatesMode = value;
  26555. if (this._scene) {
  26556. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26557. }
  26558. },
  26559. enumerable: true,
  26560. configurable: true
  26561. });
  26562. Object.defineProperty(BaseTexture.prototype, "uid", {
  26563. get: function () {
  26564. if (!this._uid) {
  26565. this._uid = BABYLON.Tools.RandomId();
  26566. }
  26567. return this._uid;
  26568. },
  26569. enumerable: true,
  26570. configurable: true
  26571. });
  26572. BaseTexture.prototype.toString = function () {
  26573. return this.name;
  26574. };
  26575. BaseTexture.prototype.getClassName = function () {
  26576. return "BaseTexture";
  26577. };
  26578. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26579. set: function (callback) {
  26580. if (this._onDisposeObserver) {
  26581. this.onDisposeObservable.remove(this._onDisposeObserver);
  26582. }
  26583. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26584. },
  26585. enumerable: true,
  26586. configurable: true
  26587. });
  26588. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26589. get: function () {
  26590. return true;
  26591. },
  26592. enumerable: true,
  26593. configurable: true
  26594. });
  26595. BaseTexture.prototype.getScene = function () {
  26596. return this._scene;
  26597. };
  26598. BaseTexture.prototype.getTextureMatrix = function () {
  26599. return BABYLON.Matrix.IdentityReadOnly;
  26600. };
  26601. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26602. return BABYLON.Matrix.IdentityReadOnly;
  26603. };
  26604. BaseTexture.prototype.getInternalTexture = function () {
  26605. return this._texture;
  26606. };
  26607. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26608. return !this.isBlocking || this.isReady();
  26609. };
  26610. BaseTexture.prototype.isReady = function () {
  26611. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26612. this.delayLoad();
  26613. return false;
  26614. }
  26615. if (this._texture) {
  26616. return this._texture.isReady;
  26617. }
  26618. return false;
  26619. };
  26620. BaseTexture.prototype.getSize = function () {
  26621. if (this._texture && this._texture.width) {
  26622. return new BABYLON.Size(this._texture.width, this._texture.height);
  26623. }
  26624. if (this._texture && this._texture._size) {
  26625. return new BABYLON.Size(this._texture._size, this._texture._size);
  26626. }
  26627. return BABYLON.Size.Zero();
  26628. };
  26629. BaseTexture.prototype.getBaseSize = function () {
  26630. if (!this.isReady() || !this._texture)
  26631. return BABYLON.Size.Zero();
  26632. if (this._texture._size) {
  26633. return new BABYLON.Size(this._texture._size, this._texture._size);
  26634. }
  26635. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26636. };
  26637. BaseTexture.prototype.scale = function (ratio) {
  26638. };
  26639. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26640. get: function () {
  26641. return false;
  26642. },
  26643. enumerable: true,
  26644. configurable: true
  26645. });
  26646. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26647. if (!this._scene) {
  26648. return null;
  26649. }
  26650. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26651. for (var index = 0; index < texturesCache.length; index++) {
  26652. var texturesCacheEntry = texturesCache[index];
  26653. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26654. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26655. texturesCacheEntry.incrementReferences();
  26656. return texturesCacheEntry;
  26657. }
  26658. }
  26659. }
  26660. return null;
  26661. };
  26662. BaseTexture.prototype._rebuild = function () {
  26663. };
  26664. BaseTexture.prototype.delayLoad = function () {
  26665. };
  26666. BaseTexture.prototype.clone = function () {
  26667. return null;
  26668. };
  26669. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26670. get: function () {
  26671. if (!this._texture) {
  26672. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26673. }
  26674. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26675. },
  26676. enumerable: true,
  26677. configurable: true
  26678. });
  26679. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26680. get: function () {
  26681. if (!this._texture) {
  26682. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26683. }
  26684. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26685. },
  26686. enumerable: true,
  26687. configurable: true
  26688. });
  26689. BaseTexture.prototype.readPixels = function (faceIndex) {
  26690. if (faceIndex === void 0) { faceIndex = 0; }
  26691. if (!this._texture) {
  26692. return null;
  26693. }
  26694. var size = this.getSize();
  26695. var scene = this.getScene();
  26696. if (!scene) {
  26697. return null;
  26698. }
  26699. var engine = scene.getEngine();
  26700. if (this._texture.isCube) {
  26701. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26702. }
  26703. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26704. };
  26705. BaseTexture.prototype.releaseInternalTexture = function () {
  26706. if (this._texture) {
  26707. this._texture.dispose();
  26708. this._texture = null;
  26709. }
  26710. };
  26711. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26712. get: function () {
  26713. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26714. return null;
  26715. }
  26716. if (!this._texture._sphericalPolynomial) {
  26717. this._texture._sphericalPolynomial =
  26718. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26719. }
  26720. return this._texture._sphericalPolynomial;
  26721. },
  26722. set: function (value) {
  26723. if (this._texture) {
  26724. this._texture._sphericalPolynomial = value;
  26725. }
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26731. get: function () {
  26732. if (this._texture) {
  26733. return this._texture._lodTextureHigh;
  26734. }
  26735. return null;
  26736. },
  26737. enumerable: true,
  26738. configurable: true
  26739. });
  26740. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26741. get: function () {
  26742. if (this._texture) {
  26743. return this._texture._lodTextureMid;
  26744. }
  26745. return null;
  26746. },
  26747. enumerable: true,
  26748. configurable: true
  26749. });
  26750. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26751. get: function () {
  26752. if (this._texture) {
  26753. return this._texture._lodTextureLow;
  26754. }
  26755. return null;
  26756. },
  26757. enumerable: true,
  26758. configurable: true
  26759. });
  26760. BaseTexture.prototype.dispose = function () {
  26761. if (!this._scene) {
  26762. return;
  26763. }
  26764. // Animations
  26765. this._scene.stopAnimation(this);
  26766. // Remove from scene
  26767. this._scene._removePendingData(this);
  26768. var index = this._scene.textures.indexOf(this);
  26769. if (index >= 0) {
  26770. this._scene.textures.splice(index, 1);
  26771. }
  26772. if (this._texture === undefined) {
  26773. return;
  26774. }
  26775. // Release
  26776. this.releaseInternalTexture();
  26777. // Callback
  26778. this.onDisposeObservable.notifyObservers(this);
  26779. this.onDisposeObservable.clear();
  26780. };
  26781. BaseTexture.prototype.serialize = function () {
  26782. if (!this.name) {
  26783. return null;
  26784. }
  26785. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26786. // Animations
  26787. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26788. return serializationObject;
  26789. };
  26790. BaseTexture.WhenAllReady = function (textures, callback) {
  26791. var numRemaining = textures.length;
  26792. if (numRemaining === 0) {
  26793. callback();
  26794. return;
  26795. }
  26796. var _loop_1 = function () {
  26797. texture = textures[i];
  26798. if (texture.isReady()) {
  26799. if (--numRemaining === 0) {
  26800. callback();
  26801. }
  26802. }
  26803. else {
  26804. onLoadObservable = texture.onLoadObservable;
  26805. var onLoadCallback_1 = function () {
  26806. onLoadObservable.removeCallback(onLoadCallback_1);
  26807. if (--numRemaining === 0) {
  26808. callback();
  26809. }
  26810. };
  26811. onLoadObservable.add(onLoadCallback_1);
  26812. }
  26813. };
  26814. var texture, onLoadObservable;
  26815. for (var i = 0; i < textures.length; i++) {
  26816. _loop_1();
  26817. }
  26818. };
  26819. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26820. __decorate([
  26821. BABYLON.serialize()
  26822. ], BaseTexture.prototype, "name", void 0);
  26823. __decorate([
  26824. BABYLON.serialize("hasAlpha")
  26825. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26826. __decorate([
  26827. BABYLON.serialize()
  26828. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26829. __decorate([
  26830. BABYLON.serialize()
  26831. ], BaseTexture.prototype, "level", void 0);
  26832. __decorate([
  26833. BABYLON.serialize()
  26834. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26835. __decorate([
  26836. BABYLON.serialize("coordinatesMode")
  26837. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26838. __decorate([
  26839. BABYLON.serialize()
  26840. ], BaseTexture.prototype, "wrapU", void 0);
  26841. __decorate([
  26842. BABYLON.serialize()
  26843. ], BaseTexture.prototype, "wrapV", void 0);
  26844. __decorate([
  26845. BABYLON.serialize()
  26846. ], BaseTexture.prototype, "wrapR", void 0);
  26847. __decorate([
  26848. BABYLON.serialize()
  26849. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26850. __decorate([
  26851. BABYLON.serialize()
  26852. ], BaseTexture.prototype, "isCube", void 0);
  26853. __decorate([
  26854. BABYLON.serialize()
  26855. ], BaseTexture.prototype, "is3D", void 0);
  26856. __decorate([
  26857. BABYLON.serialize()
  26858. ], BaseTexture.prototype, "gammaSpace", void 0);
  26859. __decorate([
  26860. BABYLON.serialize()
  26861. ], BaseTexture.prototype, "invertZ", void 0);
  26862. __decorate([
  26863. BABYLON.serialize()
  26864. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26865. __decorate([
  26866. BABYLON.serialize()
  26867. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26868. __decorate([
  26869. BABYLON.serialize()
  26870. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26871. __decorate([
  26872. BABYLON.serialize()
  26873. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26874. return BaseTexture;
  26875. }());
  26876. BABYLON.BaseTexture = BaseTexture;
  26877. })(BABYLON || (BABYLON = {}));
  26878. //# sourceMappingURL=babylon.baseTexture.js.map
  26879. var BABYLON;
  26880. (function (BABYLON) {
  26881. var Texture = /** @class */ (function (_super) {
  26882. __extends(Texture, _super);
  26883. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26884. if (noMipmap === void 0) { noMipmap = false; }
  26885. if (invertY === void 0) { invertY = true; }
  26886. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26887. if (onLoad === void 0) { onLoad = null; }
  26888. if (onError === void 0) { onError = null; }
  26889. if (buffer === void 0) { buffer = null; }
  26890. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26891. var _this = _super.call(this, scene) || this;
  26892. _this.uOffset = 0;
  26893. _this.vOffset = 0;
  26894. _this.uScale = 1.0;
  26895. _this.vScale = 1.0;
  26896. _this.uAng = 0;
  26897. _this.vAng = 0;
  26898. _this.wAng = 0;
  26899. _this._isBlocking = true;
  26900. _this.name = url || "";
  26901. _this.url = url;
  26902. _this._noMipmap = noMipmap;
  26903. _this._invertY = invertY;
  26904. _this._samplingMode = samplingMode;
  26905. _this._buffer = buffer;
  26906. _this._deleteBuffer = deleteBuffer;
  26907. if (format) {
  26908. _this._format = format;
  26909. }
  26910. scene = _this.getScene();
  26911. if (!scene) {
  26912. return _this;
  26913. }
  26914. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26915. var load = function () {
  26916. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26917. _this.onLoadObservable.notifyObservers(_this);
  26918. }
  26919. if (onLoad) {
  26920. onLoad();
  26921. }
  26922. if (!_this.isBlocking && scene) {
  26923. scene.resetCachedMaterial();
  26924. }
  26925. };
  26926. if (!_this.url) {
  26927. _this._delayedOnLoad = load;
  26928. _this._delayedOnError = onError;
  26929. return _this;
  26930. }
  26931. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26932. if (!_this._texture) {
  26933. if (!scene.useDelayedTextureLoading) {
  26934. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26935. if (deleteBuffer) {
  26936. delete _this._buffer;
  26937. }
  26938. }
  26939. else {
  26940. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26941. _this._delayedOnLoad = load;
  26942. _this._delayedOnError = onError;
  26943. }
  26944. }
  26945. else {
  26946. if (_this._texture.isReady) {
  26947. BABYLON.Tools.SetImmediate(function () { return load(); });
  26948. }
  26949. else {
  26950. _this._texture.onLoadedObservable.add(load);
  26951. }
  26952. }
  26953. return _this;
  26954. }
  26955. Object.defineProperty(Texture.prototype, "noMipmap", {
  26956. get: function () {
  26957. return this._noMipmap;
  26958. },
  26959. enumerable: true,
  26960. configurable: true
  26961. });
  26962. Object.defineProperty(Texture.prototype, "isBlocking", {
  26963. get: function () {
  26964. return this._isBlocking;
  26965. },
  26966. set: function (value) {
  26967. this._isBlocking = value;
  26968. },
  26969. enumerable: true,
  26970. configurable: true
  26971. });
  26972. Object.defineProperty(Texture.prototype, "samplingMode", {
  26973. get: function () {
  26974. return this._samplingMode;
  26975. },
  26976. enumerable: true,
  26977. configurable: true
  26978. });
  26979. Texture.prototype.updateURL = function (url) {
  26980. this.url = url;
  26981. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26982. this.delayLoad();
  26983. };
  26984. Texture.prototype.delayLoad = function () {
  26985. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26986. return;
  26987. }
  26988. var scene = this.getScene();
  26989. if (!scene) {
  26990. return;
  26991. }
  26992. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26993. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26994. if (!this._texture) {
  26995. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26996. if (this._deleteBuffer) {
  26997. delete this._buffer;
  26998. }
  26999. }
  27000. else {
  27001. if (this._delayedOnLoad) {
  27002. if (this._texture.isReady) {
  27003. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27004. }
  27005. else {
  27006. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27007. }
  27008. }
  27009. }
  27010. this._delayedOnLoad = null;
  27011. this._delayedOnError = null;
  27012. };
  27013. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27014. if (!this._texture) {
  27015. return;
  27016. }
  27017. var scene = this.getScene();
  27018. if (!scene) {
  27019. return;
  27020. }
  27021. this._samplingMode = samplingMode;
  27022. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27023. };
  27024. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27025. x *= this.uScale;
  27026. y *= this.vScale;
  27027. x -= 0.5 * this.uScale;
  27028. y -= 0.5 * this.vScale;
  27029. z -= 0.5;
  27030. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27031. t.x += 0.5 * this.uScale + this.uOffset;
  27032. t.y += 0.5 * this.vScale + this.vOffset;
  27033. t.z += 0.5;
  27034. };
  27035. Texture.prototype.getTextureMatrix = function () {
  27036. var _this = this;
  27037. if (this.uOffset === this._cachedUOffset &&
  27038. this.vOffset === this._cachedVOffset &&
  27039. this.uScale === this._cachedUScale &&
  27040. this.vScale === this._cachedVScale &&
  27041. this.uAng === this._cachedUAng &&
  27042. this.vAng === this._cachedVAng &&
  27043. this.wAng === this._cachedWAng) {
  27044. return this._cachedTextureMatrix;
  27045. }
  27046. this._cachedUOffset = this.uOffset;
  27047. this._cachedVOffset = this.vOffset;
  27048. this._cachedUScale = this.uScale;
  27049. this._cachedVScale = this.vScale;
  27050. this._cachedUAng = this.uAng;
  27051. this._cachedVAng = this.vAng;
  27052. this._cachedWAng = this.wAng;
  27053. if (!this._cachedTextureMatrix) {
  27054. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27055. this._rowGenerationMatrix = new BABYLON.Matrix();
  27056. this._t0 = BABYLON.Vector3.Zero();
  27057. this._t1 = BABYLON.Vector3.Zero();
  27058. this._t2 = BABYLON.Vector3.Zero();
  27059. }
  27060. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27061. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27062. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27063. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27064. this._t1.subtractInPlace(this._t0);
  27065. this._t2.subtractInPlace(this._t0);
  27066. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27067. this._cachedTextureMatrix.m[0] = this._t1.x;
  27068. this._cachedTextureMatrix.m[1] = this._t1.y;
  27069. this._cachedTextureMatrix.m[2] = this._t1.z;
  27070. this._cachedTextureMatrix.m[4] = this._t2.x;
  27071. this._cachedTextureMatrix.m[5] = this._t2.y;
  27072. this._cachedTextureMatrix.m[6] = this._t2.z;
  27073. this._cachedTextureMatrix.m[8] = this._t0.x;
  27074. this._cachedTextureMatrix.m[9] = this._t0.y;
  27075. this._cachedTextureMatrix.m[10] = this._t0.z;
  27076. var scene = this.getScene();
  27077. if (!scene) {
  27078. return this._cachedTextureMatrix;
  27079. }
  27080. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27081. return mat.hasTexture(_this);
  27082. });
  27083. return this._cachedTextureMatrix;
  27084. };
  27085. Texture.prototype.getReflectionTextureMatrix = function () {
  27086. var _this = this;
  27087. var scene = this.getScene();
  27088. if (!scene) {
  27089. return this._cachedTextureMatrix;
  27090. }
  27091. if (this.uOffset === this._cachedUOffset &&
  27092. this.vOffset === this._cachedVOffset &&
  27093. this.uScale === this._cachedUScale &&
  27094. this.vScale === this._cachedVScale &&
  27095. this.coordinatesMode === this._cachedCoordinatesMode) {
  27096. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27097. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27098. return this._cachedTextureMatrix;
  27099. }
  27100. }
  27101. else {
  27102. return this._cachedTextureMatrix;
  27103. }
  27104. }
  27105. if (!this._cachedTextureMatrix) {
  27106. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27107. }
  27108. if (!this._projectionModeMatrix) {
  27109. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27110. }
  27111. this._cachedUOffset = this.uOffset;
  27112. this._cachedVOffset = this.vOffset;
  27113. this._cachedUScale = this.uScale;
  27114. this._cachedVScale = this.vScale;
  27115. this._cachedCoordinatesMode = this.coordinatesMode;
  27116. switch (this.coordinatesMode) {
  27117. case Texture.PLANAR_MODE:
  27118. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27119. this._cachedTextureMatrix[0] = this.uScale;
  27120. this._cachedTextureMatrix[5] = this.vScale;
  27121. this._cachedTextureMatrix[12] = this.uOffset;
  27122. this._cachedTextureMatrix[13] = this.vOffset;
  27123. break;
  27124. case Texture.PROJECTION_MODE:
  27125. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27126. this._projectionModeMatrix.m[0] = 0.5;
  27127. this._projectionModeMatrix.m[5] = -0.5;
  27128. this._projectionModeMatrix.m[10] = 0.0;
  27129. this._projectionModeMatrix.m[12] = 0.5;
  27130. this._projectionModeMatrix.m[13] = 0.5;
  27131. this._projectionModeMatrix.m[14] = 1.0;
  27132. this._projectionModeMatrix.m[15] = 1.0;
  27133. var projectionMatrix = scene.getProjectionMatrix();
  27134. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27135. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27136. break;
  27137. default:
  27138. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27139. break;
  27140. }
  27141. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27142. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27143. });
  27144. return this._cachedTextureMatrix;
  27145. };
  27146. Texture.prototype.clone = function () {
  27147. var _this = this;
  27148. return BABYLON.SerializationHelper.Clone(function () {
  27149. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27150. }, this);
  27151. };
  27152. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27153. get: function () {
  27154. if (!this._onLoadObservable) {
  27155. this._onLoadObservable = new BABYLON.Observable();
  27156. }
  27157. return this._onLoadObservable;
  27158. },
  27159. enumerable: true,
  27160. configurable: true
  27161. });
  27162. Texture.prototype.serialize = function () {
  27163. var serializationObject = _super.prototype.serialize.call(this);
  27164. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27165. serializationObject.base64String = this._buffer;
  27166. serializationObject.name = serializationObject.name.replace("data:", "");
  27167. }
  27168. return serializationObject;
  27169. };
  27170. Texture.prototype.getClassName = function () {
  27171. return "Texture";
  27172. };
  27173. Texture.prototype.dispose = function () {
  27174. _super.prototype.dispose.call(this);
  27175. if (this.onLoadObservable) {
  27176. this.onLoadObservable.clear();
  27177. this._onLoadObservable = null;
  27178. }
  27179. this._delayedOnLoad = null;
  27180. this._delayedOnError = null;
  27181. };
  27182. // Statics
  27183. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27184. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27185. if (onLoad === void 0) { onLoad = null; }
  27186. if (onError === void 0) { onError = null; }
  27187. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27188. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27189. };
  27190. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27191. if (parsedTexture.customType) {
  27192. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27193. // Update Sampling Mode
  27194. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27195. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27196. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27197. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27198. }
  27199. }
  27200. return parsedCustomTexture;
  27201. }
  27202. if (parsedTexture.isCube) {
  27203. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27204. }
  27205. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27206. return null;
  27207. }
  27208. var texture = BABYLON.SerializationHelper.Parse(function () {
  27209. var generateMipMaps = true;
  27210. if (parsedTexture.noMipmap) {
  27211. generateMipMaps = false;
  27212. }
  27213. if (parsedTexture.mirrorPlane) {
  27214. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27215. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27216. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27217. return mirrorTexture;
  27218. }
  27219. else if (parsedTexture.isRenderTarget) {
  27220. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27221. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27222. return renderTargetTexture;
  27223. }
  27224. else {
  27225. var texture;
  27226. if (parsedTexture.base64String) {
  27227. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27228. }
  27229. else {
  27230. var url = rootUrl + parsedTexture.name;
  27231. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27232. url = parsedTexture.url;
  27233. }
  27234. texture = new Texture(url, scene, !generateMipMaps);
  27235. }
  27236. return texture;
  27237. }
  27238. }, parsedTexture, scene);
  27239. // Update Sampling Mode
  27240. if (parsedTexture.samplingMode) {
  27241. var sampling = parsedTexture.samplingMode;
  27242. if (texture._samplingMode !== sampling) {
  27243. texture.updateSamplingMode(sampling);
  27244. }
  27245. }
  27246. // Animations
  27247. if (parsedTexture.animations) {
  27248. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27249. var parsedAnimation = parsedTexture.animations[animationIndex];
  27250. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27251. }
  27252. }
  27253. return texture;
  27254. };
  27255. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27256. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27257. if (noMipmap === void 0) { noMipmap = false; }
  27258. if (invertY === void 0) { invertY = true; }
  27259. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27260. if (onLoad === void 0) { onLoad = null; }
  27261. if (onError === void 0) { onError = null; }
  27262. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27263. if (name.substr(0, 5) !== "data:") {
  27264. name = "data:" + name;
  27265. }
  27266. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27267. };
  27268. // Constants
  27269. Texture.NEAREST_SAMPLINGMODE = 1;
  27270. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27271. Texture.BILINEAR_SAMPLINGMODE = 2;
  27272. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27273. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27274. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27275. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27276. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27277. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27278. Texture.NEAREST_LINEAR = 7;
  27279. Texture.NEAREST_NEAREST = 8;
  27280. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27281. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27282. Texture.LINEAR_LINEAR = 11;
  27283. Texture.LINEAR_NEAREST = 12;
  27284. Texture.EXPLICIT_MODE = 0;
  27285. Texture.SPHERICAL_MODE = 1;
  27286. Texture.PLANAR_MODE = 2;
  27287. Texture.CUBIC_MODE = 3;
  27288. Texture.PROJECTION_MODE = 4;
  27289. Texture.SKYBOX_MODE = 5;
  27290. Texture.INVCUBIC_MODE = 6;
  27291. Texture.EQUIRECTANGULAR_MODE = 7;
  27292. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27293. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27294. Texture.CLAMP_ADDRESSMODE = 0;
  27295. Texture.WRAP_ADDRESSMODE = 1;
  27296. Texture.MIRROR_ADDRESSMODE = 2;
  27297. /**
  27298. * 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
  27299. */
  27300. Texture.UseSerializedUrlIfAny = false;
  27301. __decorate([
  27302. BABYLON.serialize()
  27303. ], Texture.prototype, "url", void 0);
  27304. __decorate([
  27305. BABYLON.serialize()
  27306. ], Texture.prototype, "uOffset", void 0);
  27307. __decorate([
  27308. BABYLON.serialize()
  27309. ], Texture.prototype, "vOffset", void 0);
  27310. __decorate([
  27311. BABYLON.serialize()
  27312. ], Texture.prototype, "uScale", void 0);
  27313. __decorate([
  27314. BABYLON.serialize()
  27315. ], Texture.prototype, "vScale", void 0);
  27316. __decorate([
  27317. BABYLON.serialize()
  27318. ], Texture.prototype, "uAng", void 0);
  27319. __decorate([
  27320. BABYLON.serialize()
  27321. ], Texture.prototype, "vAng", void 0);
  27322. __decorate([
  27323. BABYLON.serialize()
  27324. ], Texture.prototype, "wAng", void 0);
  27325. __decorate([
  27326. BABYLON.serialize()
  27327. ], Texture.prototype, "isBlocking", null);
  27328. return Texture;
  27329. }(BABYLON.BaseTexture));
  27330. BABYLON.Texture = Texture;
  27331. })(BABYLON || (BABYLON = {}));
  27332. //# sourceMappingURL=babylon.texture.js.map
  27333. var BABYLON;
  27334. (function (BABYLON) {
  27335. var _InstancesBatch = /** @class */ (function () {
  27336. function _InstancesBatch() {
  27337. this.mustReturn = false;
  27338. this.visibleInstances = new Array();
  27339. this.renderSelf = new Array();
  27340. }
  27341. return _InstancesBatch;
  27342. }());
  27343. BABYLON._InstancesBatch = _InstancesBatch;
  27344. var Mesh = /** @class */ (function (_super) {
  27345. __extends(Mesh, _super);
  27346. /**
  27347. * @constructor
  27348. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27349. * @param {Scene} scene The scene to add this mesh to.
  27350. * @param {Node} parent The parent of this mesh, if it has one
  27351. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27352. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27353. * When false, achieved by calling a clone(), also passing False.
  27354. * This will make creation of children, recursive.
  27355. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27356. */
  27357. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27358. if (scene === void 0) { scene = null; }
  27359. if (parent === void 0) { parent = null; }
  27360. if (source === void 0) { source = null; }
  27361. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27362. var _this = _super.call(this, name, scene) || this;
  27363. // Events
  27364. /**
  27365. * An event triggered before rendering the mesh
  27366. * @type {BABYLON.Observable}
  27367. */
  27368. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27369. /**
  27370. * An event triggered after rendering the mesh
  27371. * @type {BABYLON.Observable}
  27372. */
  27373. _this.onAfterRenderObservable = new BABYLON.Observable();
  27374. /**
  27375. * An event triggered before drawing the mesh
  27376. * @type {BABYLON.Observable}
  27377. */
  27378. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27379. // Members
  27380. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27381. _this.instances = new Array();
  27382. _this._LODLevels = new Array();
  27383. _this._visibleInstances = {};
  27384. _this._renderIdForInstances = new Array();
  27385. _this._batchCache = new _InstancesBatch();
  27386. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27387. // Use by builder only to know what orientation were the mesh build in.
  27388. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27389. _this.overrideMaterialSideOrientation = null;
  27390. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27391. // Will be used to save a source mesh reference, If any
  27392. _this._source = null;
  27393. scene = _this.getScene();
  27394. if (source) {
  27395. // Source mesh
  27396. _this._source = source;
  27397. // Geometry
  27398. if (source._geometry) {
  27399. source._geometry.applyToMesh(_this);
  27400. }
  27401. // Deep copy
  27402. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27403. // Metadata
  27404. if (source.metadata && source.metadata.clone) {
  27405. _this.metadata = source.metadata.clone();
  27406. }
  27407. else {
  27408. _this.metadata = source.metadata;
  27409. }
  27410. // Tags
  27411. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27412. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27413. }
  27414. // Parent
  27415. _this.parent = source.parent;
  27416. // Pivot
  27417. _this.setPivotMatrix(source.getPivotMatrix());
  27418. _this.id = name + "." + source.id;
  27419. // Material
  27420. _this.material = source.material;
  27421. var index;
  27422. if (!doNotCloneChildren) {
  27423. // Children
  27424. var directDescendants = source.getDescendants(true);
  27425. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27426. var child = directDescendants[index_1];
  27427. if (child.clone) {
  27428. child.clone(name + "." + child.name, _this);
  27429. }
  27430. }
  27431. }
  27432. // Physics clone
  27433. var physicsEngine = _this.getScene().getPhysicsEngine();
  27434. if (clonePhysicsImpostor && physicsEngine) {
  27435. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27436. if (impostor) {
  27437. _this.physicsImpostor = impostor.clone(_this);
  27438. }
  27439. }
  27440. // Particles
  27441. for (index = 0; index < scene.particleSystems.length; index++) {
  27442. var system = scene.particleSystems[index];
  27443. if (system.emitter === source) {
  27444. system.clone(system.name, _this);
  27445. }
  27446. }
  27447. _this.computeWorldMatrix(true);
  27448. }
  27449. // Parent
  27450. if (parent !== null) {
  27451. _this.parent = parent;
  27452. }
  27453. return _this;
  27454. }
  27455. Object.defineProperty(Mesh, "FRONTSIDE", {
  27456. /**
  27457. * Mesh side orientation : usually the external or front surface
  27458. */
  27459. get: function () {
  27460. return Mesh._FRONTSIDE;
  27461. },
  27462. enumerable: true,
  27463. configurable: true
  27464. });
  27465. Object.defineProperty(Mesh, "BACKSIDE", {
  27466. /**
  27467. * Mesh side orientation : usually the internal or back surface
  27468. */
  27469. get: function () {
  27470. return Mesh._BACKSIDE;
  27471. },
  27472. enumerable: true,
  27473. configurable: true
  27474. });
  27475. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27476. /**
  27477. * Mesh side orientation : both internal and external or front and back surfaces
  27478. */
  27479. get: function () {
  27480. return Mesh._DOUBLESIDE;
  27481. },
  27482. enumerable: true,
  27483. configurable: true
  27484. });
  27485. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27486. /**
  27487. * Mesh side orientation : by default, `FRONTSIDE`
  27488. */
  27489. get: function () {
  27490. return Mesh._DEFAULTSIDE;
  27491. },
  27492. enumerable: true,
  27493. configurable: true
  27494. });
  27495. Object.defineProperty(Mesh, "NO_CAP", {
  27496. /**
  27497. * Mesh cap setting : no cap
  27498. */
  27499. get: function () {
  27500. return Mesh._NO_CAP;
  27501. },
  27502. enumerable: true,
  27503. configurable: true
  27504. });
  27505. Object.defineProperty(Mesh, "CAP_START", {
  27506. /**
  27507. * Mesh cap setting : one cap at the beginning of the mesh
  27508. */
  27509. get: function () {
  27510. return Mesh._CAP_START;
  27511. },
  27512. enumerable: true,
  27513. configurable: true
  27514. });
  27515. Object.defineProperty(Mesh, "CAP_END", {
  27516. /**
  27517. * Mesh cap setting : one cap at the end of the mesh
  27518. */
  27519. get: function () {
  27520. return Mesh._CAP_END;
  27521. },
  27522. enumerable: true,
  27523. configurable: true
  27524. });
  27525. Object.defineProperty(Mesh, "CAP_ALL", {
  27526. /**
  27527. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27528. */
  27529. get: function () {
  27530. return Mesh._CAP_ALL;
  27531. },
  27532. enumerable: true,
  27533. configurable: true
  27534. });
  27535. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27536. set: function (callback) {
  27537. if (this._onBeforeDrawObserver) {
  27538. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27539. }
  27540. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27541. },
  27542. enumerable: true,
  27543. configurable: true
  27544. });
  27545. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27546. get: function () {
  27547. return this._morphTargetManager;
  27548. },
  27549. set: function (value) {
  27550. if (this._morphTargetManager === value) {
  27551. return;
  27552. }
  27553. this._morphTargetManager = value;
  27554. this._syncGeometryWithMorphTargetManager();
  27555. },
  27556. enumerable: true,
  27557. configurable: true
  27558. });
  27559. Object.defineProperty(Mesh.prototype, "source", {
  27560. get: function () {
  27561. return this._source;
  27562. },
  27563. enumerable: true,
  27564. configurable: true
  27565. });
  27566. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27567. get: function () {
  27568. return this._unIndexed;
  27569. },
  27570. set: function (value) {
  27571. if (this._unIndexed !== value) {
  27572. this._unIndexed = value;
  27573. this._markSubMeshesAsAttributesDirty();
  27574. }
  27575. },
  27576. enumerable: true,
  27577. configurable: true
  27578. });
  27579. // Methods
  27580. /**
  27581. * Returns the string "Mesh".
  27582. */
  27583. Mesh.prototype.getClassName = function () {
  27584. return "Mesh";
  27585. };
  27586. /**
  27587. * Returns a string.
  27588. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27589. */
  27590. Mesh.prototype.toString = function (fullDetails) {
  27591. var ret = _super.prototype.toString.call(this, fullDetails);
  27592. ret += ", n vertices: " + this.getTotalVertices();
  27593. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27594. if (this.animations) {
  27595. for (var i = 0; i < this.animations.length; i++) {
  27596. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27597. }
  27598. }
  27599. if (fullDetails) {
  27600. if (this._geometry) {
  27601. var ib = this.getIndices();
  27602. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27603. if (vb && ib) {
  27604. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27605. }
  27606. }
  27607. else {
  27608. ret += ", flat shading: UNKNOWN";
  27609. }
  27610. }
  27611. return ret;
  27612. };
  27613. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27614. /**
  27615. * True if the mesh has some Levels Of Details (LOD).
  27616. * Returns a boolean.
  27617. */
  27618. get: function () {
  27619. return this._LODLevels.length > 0;
  27620. },
  27621. enumerable: true,
  27622. configurable: true
  27623. });
  27624. /**
  27625. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27626. * @returns an array of {BABYLON.MeshLODLevel}
  27627. */
  27628. Mesh.prototype.getLODLevels = function () {
  27629. return this._LODLevels;
  27630. };
  27631. Mesh.prototype._sortLODLevels = function () {
  27632. this._LODLevels.sort(function (a, b) {
  27633. if (a.distance < b.distance) {
  27634. return 1;
  27635. }
  27636. if (a.distance > b.distance) {
  27637. return -1;
  27638. }
  27639. return 0;
  27640. });
  27641. };
  27642. /**
  27643. * Add a mesh as LOD level triggered at the given distance.
  27644. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27645. * @param {number} distance The distance from the center of the object to show this level
  27646. * @param {Mesh} mesh The mesh to be added as LOD level
  27647. * @return {Mesh} This mesh (for chaining)
  27648. */
  27649. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27650. if (mesh && mesh._masterMesh) {
  27651. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27652. return this;
  27653. }
  27654. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27655. this._LODLevels.push(level);
  27656. if (mesh) {
  27657. mesh._masterMesh = this;
  27658. }
  27659. this._sortLODLevels();
  27660. return this;
  27661. };
  27662. /**
  27663. * Returns the LOD level mesh at the passed distance or null if not found.
  27664. * It is related to the method `addLODLevel(distance, mesh)`.
  27665. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27666. * Returns an object Mesh or `null`.
  27667. */
  27668. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27669. for (var index = 0; index < this._LODLevels.length; index++) {
  27670. var level = this._LODLevels[index];
  27671. if (level.distance === distance) {
  27672. return level.mesh;
  27673. }
  27674. }
  27675. return null;
  27676. };
  27677. /**
  27678. * Remove a mesh from the LOD array
  27679. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27680. * @param {Mesh} mesh The mesh to be removed.
  27681. * @return {Mesh} This mesh (for chaining)
  27682. */
  27683. Mesh.prototype.removeLODLevel = function (mesh) {
  27684. for (var index = 0; index < this._LODLevels.length; index++) {
  27685. if (this._LODLevels[index].mesh === mesh) {
  27686. this._LODLevels.splice(index, 1);
  27687. if (mesh) {
  27688. mesh._masterMesh = null;
  27689. }
  27690. }
  27691. }
  27692. this._sortLODLevels();
  27693. return this;
  27694. };
  27695. /**
  27696. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27697. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27698. */
  27699. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27700. if (!this._LODLevels || this._LODLevels.length === 0) {
  27701. return this;
  27702. }
  27703. var bSphere;
  27704. if (boundingSphere) {
  27705. bSphere = boundingSphere;
  27706. }
  27707. else {
  27708. var boundingInfo = this.getBoundingInfo();
  27709. bSphere = boundingInfo.boundingSphere;
  27710. }
  27711. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27712. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27713. if (this.onLODLevelSelection) {
  27714. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27715. }
  27716. return this;
  27717. }
  27718. for (var index = 0; index < this._LODLevels.length; index++) {
  27719. var level = this._LODLevels[index];
  27720. if (level.distance < distanceToCamera) {
  27721. if (level.mesh) {
  27722. level.mesh._preActivate();
  27723. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27724. }
  27725. if (this.onLODLevelSelection) {
  27726. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27727. }
  27728. return level.mesh;
  27729. }
  27730. }
  27731. if (this.onLODLevelSelection) {
  27732. this.onLODLevelSelection(distanceToCamera, this, this);
  27733. }
  27734. return this;
  27735. };
  27736. Object.defineProperty(Mesh.prototype, "geometry", {
  27737. /**
  27738. * Returns the mesh internal Geometry object.
  27739. */
  27740. get: function () {
  27741. return this._geometry;
  27742. },
  27743. enumerable: true,
  27744. configurable: true
  27745. });
  27746. /**
  27747. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27748. */
  27749. Mesh.prototype.getTotalVertices = function () {
  27750. if (this._geometry === null || this._geometry === undefined) {
  27751. return 0;
  27752. }
  27753. return this._geometry.getTotalVertices();
  27754. };
  27755. /**
  27756. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27757. * 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.
  27758. * You can force the copy with forceCopy === true
  27759. * Returns null if the mesh has no geometry or no vertex buffer.
  27760. * Possible `kind` values :
  27761. * - BABYLON.VertexBuffer.PositionKind
  27762. * - BABYLON.VertexBuffer.UVKind
  27763. * - BABYLON.VertexBuffer.UV2Kind
  27764. * - BABYLON.VertexBuffer.UV3Kind
  27765. * - BABYLON.VertexBuffer.UV4Kind
  27766. * - BABYLON.VertexBuffer.UV5Kind
  27767. * - BABYLON.VertexBuffer.UV6Kind
  27768. * - BABYLON.VertexBuffer.ColorKind
  27769. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27770. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27771. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27772. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27773. */
  27774. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27775. if (!this._geometry) {
  27776. return null;
  27777. }
  27778. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27779. };
  27780. /**
  27781. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27782. * Returns `null` if the mesh has no geometry.
  27783. * Possible `kind` values :
  27784. * - BABYLON.VertexBuffer.PositionKind
  27785. * - BABYLON.VertexBuffer.UVKind
  27786. * - BABYLON.VertexBuffer.UV2Kind
  27787. * - BABYLON.VertexBuffer.UV3Kind
  27788. * - BABYLON.VertexBuffer.UV4Kind
  27789. * - BABYLON.VertexBuffer.UV5Kind
  27790. * - BABYLON.VertexBuffer.UV6Kind
  27791. * - BABYLON.VertexBuffer.ColorKind
  27792. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27793. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27794. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27795. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27796. */
  27797. Mesh.prototype.getVertexBuffer = function (kind) {
  27798. if (!this._geometry) {
  27799. return null;
  27800. }
  27801. return this._geometry.getVertexBuffer(kind);
  27802. };
  27803. /**
  27804. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27805. * Possible `kind` values :
  27806. * - BABYLON.VertexBuffer.PositionKind
  27807. * - BABYLON.VertexBuffer.UVKind
  27808. * - BABYLON.VertexBuffer.UV2Kind
  27809. * - BABYLON.VertexBuffer.UV3Kind
  27810. * - BABYLON.VertexBuffer.UV4Kind
  27811. * - BABYLON.VertexBuffer.UV5Kind
  27812. * - BABYLON.VertexBuffer.UV6Kind
  27813. * - BABYLON.VertexBuffer.ColorKind
  27814. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27815. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27816. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27817. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27818. */
  27819. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27820. if (!this._geometry) {
  27821. if (this._delayInfo) {
  27822. return this._delayInfo.indexOf(kind) !== -1;
  27823. }
  27824. return false;
  27825. }
  27826. return this._geometry.isVerticesDataPresent(kind);
  27827. };
  27828. /**
  27829. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27830. * Possible `kind` values :
  27831. * - BABYLON.VertexBuffer.PositionKind
  27832. * - BABYLON.VertexBuffer.UVKind
  27833. * - BABYLON.VertexBuffer.UV2Kind
  27834. * - BABYLON.VertexBuffer.UV3Kind
  27835. * - BABYLON.VertexBuffer.UV4Kind
  27836. * - BABYLON.VertexBuffer.UV5Kind
  27837. * - BABYLON.VertexBuffer.UV6Kind
  27838. * - BABYLON.VertexBuffer.ColorKind
  27839. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27840. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27841. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27842. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27843. */
  27844. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27845. if (!this._geometry) {
  27846. if (this._delayInfo) {
  27847. return this._delayInfo.indexOf(kind) !== -1;
  27848. }
  27849. return false;
  27850. }
  27851. return this._geometry.isVertexBufferUpdatable(kind);
  27852. };
  27853. /**
  27854. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27855. * Possible `kind` values :
  27856. * - BABYLON.VertexBuffer.PositionKind
  27857. * - BABYLON.VertexBuffer.UVKind
  27858. * - BABYLON.VertexBuffer.UV2Kind
  27859. * - BABYLON.VertexBuffer.UV3Kind
  27860. * - BABYLON.VertexBuffer.UV4Kind
  27861. * - BABYLON.VertexBuffer.UV5Kind
  27862. * - BABYLON.VertexBuffer.UV6Kind
  27863. * - BABYLON.VertexBuffer.ColorKind
  27864. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27865. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27866. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27867. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27868. */
  27869. Mesh.prototype.getVerticesDataKinds = function () {
  27870. if (!this._geometry) {
  27871. var result = new Array();
  27872. if (this._delayInfo) {
  27873. this._delayInfo.forEach(function (kind, index, array) {
  27874. result.push(kind);
  27875. });
  27876. }
  27877. return result;
  27878. }
  27879. return this._geometry.getVerticesDataKinds();
  27880. };
  27881. /**
  27882. * Returns a positive integer : the total number of indices in this mesh geometry.
  27883. * Returns zero if the mesh has no geometry.
  27884. */
  27885. Mesh.prototype.getTotalIndices = function () {
  27886. if (!this._geometry) {
  27887. return 0;
  27888. }
  27889. return this._geometry.getTotalIndices();
  27890. };
  27891. /**
  27892. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27893. * 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.
  27894. * Returns an empty array if the mesh has no geometry.
  27895. */
  27896. Mesh.prototype.getIndices = function (copyWhenShared) {
  27897. if (!this._geometry) {
  27898. return [];
  27899. }
  27900. return this._geometry.getIndices(copyWhenShared);
  27901. };
  27902. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27903. get: function () {
  27904. return this._masterMesh !== null && this._masterMesh !== undefined;
  27905. },
  27906. enumerable: true,
  27907. configurable: true
  27908. });
  27909. /**
  27910. * Determine if the current mesh is ready to be rendered
  27911. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27912. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27913. * @returns true if all associated assets are ready (material, textures, shaders)
  27914. */
  27915. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27916. if (completeCheck === void 0) { completeCheck = false; }
  27917. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27918. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27919. return false;
  27920. }
  27921. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27922. return false;
  27923. }
  27924. if (!this.subMeshes || this.subMeshes.length === 0) {
  27925. return true;
  27926. }
  27927. if (!completeCheck) {
  27928. return true;
  27929. }
  27930. var engine = this.getEngine();
  27931. var scene = this.getScene();
  27932. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27933. this.computeWorldMatrix();
  27934. var mat = this.material || scene.defaultMaterial;
  27935. if (mat) {
  27936. if (mat.storeEffectOnSubMeshes) {
  27937. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27938. var subMesh = _a[_i];
  27939. var effectiveMaterial = subMesh.getMaterial();
  27940. if (effectiveMaterial) {
  27941. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27942. return false;
  27943. }
  27944. }
  27945. }
  27946. }
  27947. else {
  27948. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27949. return false;
  27950. }
  27951. }
  27952. }
  27953. // Shadows
  27954. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27955. var light = _c[_b];
  27956. var generator = light.getShadowGenerator();
  27957. if (generator) {
  27958. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27959. var subMesh = _e[_d];
  27960. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27961. return false;
  27962. }
  27963. }
  27964. }
  27965. }
  27966. // LOD
  27967. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27968. var lod = _g[_f];
  27969. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27970. return false;
  27971. }
  27972. }
  27973. return true;
  27974. };
  27975. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27976. /**
  27977. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27978. * This property is pertinent only for updatable parametric shapes.
  27979. */
  27980. get: function () {
  27981. return this._areNormalsFrozen;
  27982. },
  27983. enumerable: true,
  27984. configurable: true
  27985. });
  27986. /**
  27987. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27988. * It has no effect at all on other shapes.
  27989. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27990. * Returns the Mesh.
  27991. */
  27992. Mesh.prototype.freezeNormals = function () {
  27993. this._areNormalsFrozen = true;
  27994. return this;
  27995. };
  27996. /**
  27997. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27998. * It has no effect at all on other shapes.
  27999. * It reactivates the mesh normals computation if it was previously frozen.
  28000. * Returns the Mesh.
  28001. */
  28002. Mesh.prototype.unfreezeNormals = function () {
  28003. this._areNormalsFrozen = false;
  28004. return this;
  28005. };
  28006. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28007. /**
  28008. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28009. */
  28010. set: function (count) {
  28011. this._overridenInstanceCount = count;
  28012. },
  28013. enumerable: true,
  28014. configurable: true
  28015. });
  28016. // Methods
  28017. Mesh.prototype._preActivate = function () {
  28018. var sceneRenderId = this.getScene().getRenderId();
  28019. if (this._preActivateId === sceneRenderId) {
  28020. return this;
  28021. }
  28022. this._preActivateId = sceneRenderId;
  28023. this._visibleInstances = null;
  28024. return this;
  28025. };
  28026. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28027. if (this._visibleInstances) {
  28028. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28029. }
  28030. return this;
  28031. };
  28032. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28033. if (!this._visibleInstances) {
  28034. this._visibleInstances = {};
  28035. this._visibleInstances.defaultRenderId = renderId;
  28036. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28037. }
  28038. if (!this._visibleInstances[renderId]) {
  28039. this._visibleInstances[renderId] = new Array();
  28040. }
  28041. this._visibleInstances[renderId].push(instance);
  28042. return this;
  28043. };
  28044. /**
  28045. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28046. * This means the mesh underlying bounding box and sphere are recomputed.
  28047. * Returns the Mesh.
  28048. */
  28049. Mesh.prototype.refreshBoundingInfo = function () {
  28050. return this._refreshBoundingInfo(false);
  28051. };
  28052. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28053. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28054. return this;
  28055. }
  28056. var data = this._getPositionData(applySkeleton);
  28057. if (data) {
  28058. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28059. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28060. }
  28061. if (this.subMeshes) {
  28062. for (var index = 0; index < this.subMeshes.length; index++) {
  28063. this.subMeshes[index].refreshBoundingInfo();
  28064. }
  28065. }
  28066. this._updateBoundingInfo();
  28067. return this;
  28068. };
  28069. Mesh.prototype._getPositionData = function (applySkeleton) {
  28070. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28071. if (data && applySkeleton && this.skeleton) {
  28072. data = BABYLON.Tools.Slice(data);
  28073. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28074. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28075. if (matricesWeightsData && matricesIndicesData) {
  28076. var needExtras = this.numBoneInfluencers > 4;
  28077. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28078. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28079. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28080. var tempVector = BABYLON.Tmp.Vector3[0];
  28081. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28082. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28083. var matWeightIdx = 0;
  28084. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28085. finalMatrix.reset();
  28086. var inf;
  28087. var weight;
  28088. for (inf = 0; inf < 4; inf++) {
  28089. weight = matricesWeightsData[matWeightIdx + inf];
  28090. if (weight <= 0)
  28091. break;
  28092. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28093. finalMatrix.addToSelf(tempMatrix);
  28094. }
  28095. if (needExtras) {
  28096. for (inf = 0; inf < 4; inf++) {
  28097. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28098. if (weight <= 0)
  28099. break;
  28100. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28101. finalMatrix.addToSelf(tempMatrix);
  28102. }
  28103. }
  28104. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28105. tempVector.toArray(data, index);
  28106. }
  28107. }
  28108. }
  28109. return data;
  28110. };
  28111. Mesh.prototype._createGlobalSubMesh = function (force) {
  28112. var totalVertices = this.getTotalVertices();
  28113. if (!totalVertices || !this.getIndices()) {
  28114. return null;
  28115. }
  28116. // Check if we need to recreate the submeshes
  28117. if (this.subMeshes && this.subMeshes.length > 0) {
  28118. var ib = this.getIndices();
  28119. if (!ib) {
  28120. return null;
  28121. }
  28122. var totalIndices = ib.length;
  28123. var needToRecreate = false;
  28124. if (force) {
  28125. needToRecreate = true;
  28126. }
  28127. else {
  28128. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28129. var submesh = _a[_i];
  28130. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28131. needToRecreate = true;
  28132. break;
  28133. }
  28134. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28135. needToRecreate = true;
  28136. break;
  28137. }
  28138. }
  28139. }
  28140. if (!needToRecreate) {
  28141. return this.subMeshes[0];
  28142. }
  28143. }
  28144. this.releaseSubMeshes();
  28145. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28146. };
  28147. Mesh.prototype.subdivide = function (count) {
  28148. if (count < 1) {
  28149. return;
  28150. }
  28151. var totalIndices = this.getTotalIndices();
  28152. var subdivisionSize = (totalIndices / count) | 0;
  28153. var offset = 0;
  28154. // Ensure that subdivisionSize is a multiple of 3
  28155. while (subdivisionSize % 3 !== 0) {
  28156. subdivisionSize++;
  28157. }
  28158. this.releaseSubMeshes();
  28159. for (var index = 0; index < count; index++) {
  28160. if (offset >= totalIndices) {
  28161. break;
  28162. }
  28163. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28164. offset += subdivisionSize;
  28165. }
  28166. this.synchronizeInstances();
  28167. };
  28168. /**
  28169. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28170. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28171. * The `data` are either a numeric array either a Float32Array.
  28172. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28173. * 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).
  28174. * Note that a new underlying VertexBuffer object is created each call.
  28175. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28176. *
  28177. * Possible `kind` values :
  28178. * - BABYLON.VertexBuffer.PositionKind
  28179. * - BABYLON.VertexBuffer.UVKind
  28180. * - BABYLON.VertexBuffer.UV2Kind
  28181. * - BABYLON.VertexBuffer.UV3Kind
  28182. * - BABYLON.VertexBuffer.UV4Kind
  28183. * - BABYLON.VertexBuffer.UV5Kind
  28184. * - BABYLON.VertexBuffer.UV6Kind
  28185. * - BABYLON.VertexBuffer.ColorKind
  28186. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28187. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28188. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28189. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28190. *
  28191. * Returns the Mesh.
  28192. */
  28193. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28194. if (updatable === void 0) { updatable = false; }
  28195. if (!this._geometry) {
  28196. var vertexData = new BABYLON.VertexData();
  28197. vertexData.set(data, kind);
  28198. var scene = this.getScene();
  28199. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28200. }
  28201. else {
  28202. this._geometry.setVerticesData(kind, data, updatable, stride);
  28203. }
  28204. return this;
  28205. };
  28206. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28207. if (updatable === void 0) { updatable = true; }
  28208. var vb = this.getVertexBuffer(kind);
  28209. if (!vb || vb.isUpdatable() === updatable) {
  28210. return;
  28211. }
  28212. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28213. };
  28214. /**
  28215. * Sets the mesh VertexBuffer.
  28216. * Returns the Mesh.
  28217. */
  28218. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28219. if (!this._geometry) {
  28220. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28221. }
  28222. this._geometry.setVerticesBuffer(buffer);
  28223. return this;
  28224. };
  28225. /**
  28226. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28227. * If the mesh has no geometry, it is simply returned as it is.
  28228. * The `data` are either a numeric array either a Float32Array.
  28229. * No new underlying VertexBuffer object is created.
  28230. * 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.
  28231. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28232. *
  28233. * Possible `kind` values :
  28234. * - BABYLON.VertexBuffer.PositionKind
  28235. * - BABYLON.VertexBuffer.UVKind
  28236. * - BABYLON.VertexBuffer.UV2Kind
  28237. * - BABYLON.VertexBuffer.UV3Kind
  28238. * - BABYLON.VertexBuffer.UV4Kind
  28239. * - BABYLON.VertexBuffer.UV5Kind
  28240. * - BABYLON.VertexBuffer.UV6Kind
  28241. * - BABYLON.VertexBuffer.ColorKind
  28242. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28243. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28244. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28245. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28246. *
  28247. * Returns the Mesh.
  28248. */
  28249. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28250. if (!this._geometry) {
  28251. return this;
  28252. }
  28253. if (!makeItUnique) {
  28254. this._geometry.updateVerticesData(kind, data, updateExtends);
  28255. }
  28256. else {
  28257. this.makeGeometryUnique();
  28258. this.updateVerticesData(kind, data, updateExtends, false);
  28259. }
  28260. return this;
  28261. };
  28262. /**
  28263. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28264. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28265. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28266. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28267. * Returns the Mesh.
  28268. */
  28269. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28270. if (computeNormals === void 0) { computeNormals = true; }
  28271. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28272. if (!positions) {
  28273. return this;
  28274. }
  28275. positionFunction(positions);
  28276. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28277. if (computeNormals) {
  28278. var indices = this.getIndices();
  28279. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28280. if (!normals) {
  28281. return this;
  28282. }
  28283. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28284. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28285. }
  28286. return this;
  28287. };
  28288. /**
  28289. * Creates a un-shared specific occurence of the geometry for the mesh.
  28290. * Returns the Mesh.
  28291. */
  28292. Mesh.prototype.makeGeometryUnique = function () {
  28293. if (!this._geometry) {
  28294. return this;
  28295. }
  28296. var oldGeometry = this._geometry;
  28297. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28298. oldGeometry.releaseForMesh(this, true);
  28299. geometry.applyToMesh(this);
  28300. return this;
  28301. };
  28302. /**
  28303. * Sets the mesh indices.
  28304. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28305. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28306. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28307. * This method creates a new index buffer each call.
  28308. * Returns the Mesh.
  28309. */
  28310. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28311. if (totalVertices === void 0) { totalVertices = null; }
  28312. if (updatable === void 0) { updatable = false; }
  28313. if (!this._geometry) {
  28314. var vertexData = new BABYLON.VertexData();
  28315. vertexData.indices = indices;
  28316. var scene = this.getScene();
  28317. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28318. }
  28319. else {
  28320. this._geometry.setIndices(indices, totalVertices, updatable);
  28321. }
  28322. return this;
  28323. };
  28324. /**
  28325. * Update the current index buffer
  28326. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28327. * Returns the Mesh.
  28328. */
  28329. Mesh.prototype.updateIndices = function (indices, offset) {
  28330. if (!this._geometry) {
  28331. return this;
  28332. }
  28333. this._geometry.updateIndices(indices, offset);
  28334. return this;
  28335. };
  28336. /**
  28337. * Invert the geometry to move from a right handed system to a left handed one.
  28338. * Returns the Mesh.
  28339. */
  28340. Mesh.prototype.toLeftHanded = function () {
  28341. if (!this._geometry) {
  28342. return this;
  28343. }
  28344. this._geometry.toLeftHanded();
  28345. return this;
  28346. };
  28347. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28348. if (!this._geometry) {
  28349. return this;
  28350. }
  28351. var engine = this.getScene().getEngine();
  28352. // Wireframe
  28353. var indexToBind;
  28354. if (this._unIndexed) {
  28355. indexToBind = null;
  28356. }
  28357. else {
  28358. switch (fillMode) {
  28359. case BABYLON.Material.PointFillMode:
  28360. indexToBind = null;
  28361. break;
  28362. case BABYLON.Material.WireFrameFillMode:
  28363. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28364. break;
  28365. default:
  28366. case BABYLON.Material.TriangleFillMode:
  28367. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28368. break;
  28369. }
  28370. }
  28371. // VBOs
  28372. this._geometry._bind(effect, indexToBind);
  28373. return this;
  28374. };
  28375. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28376. if (alternate === void 0) { alternate = false; }
  28377. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28378. return this;
  28379. }
  28380. this.onBeforeDrawObservable.notifyObservers(this);
  28381. var scene = this.getScene();
  28382. var engine = scene.getEngine();
  28383. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28384. // or triangles as points
  28385. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28386. }
  28387. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28388. // Triangles as wireframe
  28389. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28390. }
  28391. else {
  28392. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28393. }
  28394. if (scene._isAlternateRenderingEnabled && !alternate) {
  28395. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28396. if (!effect || !scene.activeCamera) {
  28397. return this;
  28398. }
  28399. scene._switchToAlternateCameraConfiguration(true);
  28400. this._effectiveMaterial.bindView(effect);
  28401. this._effectiveMaterial.bindViewProjection(effect);
  28402. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28403. this._draw(subMesh, fillMode, instancesCount, true);
  28404. engine.setViewport(scene.activeCamera.viewport);
  28405. scene._switchToAlternateCameraConfiguration(false);
  28406. this._effectiveMaterial.bindView(effect);
  28407. this._effectiveMaterial.bindViewProjection(effect);
  28408. }
  28409. return this;
  28410. };
  28411. /**
  28412. * Registers for this mesh a javascript function called just before the rendering process.
  28413. * This function is passed the current mesh.
  28414. * Return the Mesh.
  28415. */
  28416. Mesh.prototype.registerBeforeRender = function (func) {
  28417. this.onBeforeRenderObservable.add(func);
  28418. return this;
  28419. };
  28420. /**
  28421. * Disposes a previously registered javascript function called before the rendering.
  28422. * This function is passed the current mesh.
  28423. * Returns the Mesh.
  28424. */
  28425. Mesh.prototype.unregisterBeforeRender = function (func) {
  28426. this.onBeforeRenderObservable.removeCallback(func);
  28427. return this;
  28428. };
  28429. /**
  28430. * Registers for this mesh a javascript function called just after the rendering is complete.
  28431. * This function is passed the current mesh.
  28432. * Returns the Mesh.
  28433. */
  28434. Mesh.prototype.registerAfterRender = function (func) {
  28435. this.onAfterRenderObservable.add(func);
  28436. return this;
  28437. };
  28438. /**
  28439. * Disposes a previously registered javascript function called after the rendering.
  28440. * This function is passed the current mesh.
  28441. * Return the Mesh.
  28442. */
  28443. Mesh.prototype.unregisterAfterRender = function (func) {
  28444. this.onAfterRenderObservable.removeCallback(func);
  28445. return this;
  28446. };
  28447. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28448. var scene = this.getScene();
  28449. this._batchCache.mustReturn = false;
  28450. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28451. this._batchCache.visibleInstances[subMeshId] = null;
  28452. if (this._visibleInstances) {
  28453. var currentRenderId = scene.getRenderId();
  28454. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28455. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28456. var selfRenderId = this._renderId;
  28457. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28458. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28459. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28460. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28461. }
  28462. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28463. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28464. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28465. this._batchCache.mustReturn = true;
  28466. return this._batchCache;
  28467. }
  28468. if (currentRenderId !== selfRenderId) {
  28469. this._batchCache.renderSelf[subMeshId] = false;
  28470. }
  28471. }
  28472. this._renderIdForInstances[subMeshId] = currentRenderId;
  28473. }
  28474. return this._batchCache;
  28475. };
  28476. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28477. var visibleInstances = batch.visibleInstances[subMesh._id];
  28478. if (!visibleInstances) {
  28479. return this;
  28480. }
  28481. var matricesCount = visibleInstances.length + 1;
  28482. var bufferSize = matricesCount * 16 * 4;
  28483. var currentInstancesBufferSize = this._instancesBufferSize;
  28484. var instancesBuffer = this._instancesBuffer;
  28485. while (this._instancesBufferSize < bufferSize) {
  28486. this._instancesBufferSize *= 2;
  28487. }
  28488. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28489. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28490. }
  28491. var offset = 0;
  28492. var instancesCount = 0;
  28493. var world = this.getWorldMatrix();
  28494. if (batch.renderSelf[subMesh._id]) {
  28495. world.copyToArray(this._instancesData, offset);
  28496. offset += 16;
  28497. instancesCount++;
  28498. }
  28499. if (visibleInstances) {
  28500. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28501. var instance = visibleInstances[instanceIndex];
  28502. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28503. offset += 16;
  28504. instancesCount++;
  28505. }
  28506. }
  28507. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28508. if (instancesBuffer) {
  28509. instancesBuffer.dispose();
  28510. }
  28511. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28512. this._instancesBuffer = instancesBuffer;
  28513. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28514. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28515. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28516. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28517. }
  28518. else {
  28519. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28520. }
  28521. this._bind(subMesh, effect, fillMode);
  28522. this._draw(subMesh, fillMode, instancesCount);
  28523. engine.unbindInstanceAttributes();
  28524. return this;
  28525. };
  28526. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28527. var scene = this.getScene();
  28528. var engine = scene.getEngine();
  28529. if (hardwareInstancedRendering) {
  28530. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28531. }
  28532. else {
  28533. if (batch.renderSelf[subMesh._id]) {
  28534. // Draw
  28535. if (onBeforeDraw) {
  28536. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28537. }
  28538. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28539. }
  28540. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28541. if (visibleInstancesForSubMesh) {
  28542. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28543. var instance = visibleInstancesForSubMesh[instanceIndex];
  28544. // World
  28545. var world = instance.getWorldMatrix();
  28546. if (onBeforeDraw) {
  28547. onBeforeDraw(true, world, effectiveMaterial);
  28548. }
  28549. // Draw
  28550. this._draw(subMesh, fillMode);
  28551. }
  28552. }
  28553. }
  28554. return this;
  28555. };
  28556. /**
  28557. * Triggers the draw call for the mesh.
  28558. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28559. * Returns the Mesh.
  28560. */
  28561. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28562. this.checkOcclusionQuery();
  28563. if (this._isOccluded) {
  28564. return this;
  28565. }
  28566. var scene = this.getScene();
  28567. // Managing instances
  28568. var batch = this._getInstancesRenderList(subMesh._id);
  28569. if (batch.mustReturn) {
  28570. return this;
  28571. }
  28572. // Checking geometry state
  28573. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28574. return this;
  28575. }
  28576. this.onBeforeRenderObservable.notifyObservers(this);
  28577. var engine = scene.getEngine();
  28578. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28579. // Material
  28580. var material = subMesh.getMaterial();
  28581. if (!material) {
  28582. return this;
  28583. }
  28584. this._effectiveMaterial = material;
  28585. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28586. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28587. return this;
  28588. }
  28589. }
  28590. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28591. return this;
  28592. }
  28593. // Alpha mode
  28594. if (enableAlphaMode) {
  28595. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28596. }
  28597. // Outline - step 1
  28598. var savedDepthWrite = engine.getDepthWrite();
  28599. if (this.renderOutline) {
  28600. engine.setDepthWrite(false);
  28601. scene.getOutlineRenderer().render(subMesh, batch);
  28602. engine.setDepthWrite(savedDepthWrite);
  28603. }
  28604. var effect;
  28605. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28606. effect = subMesh.effect;
  28607. }
  28608. else {
  28609. effect = this._effectiveMaterial.getEffect();
  28610. }
  28611. if (!effect) {
  28612. return this;
  28613. }
  28614. var sideOrientation = this.overrideMaterialSideOrientation;
  28615. if (sideOrientation == null) {
  28616. sideOrientation = this._effectiveMaterial.sideOrientation;
  28617. if (this._getWorldMatrixDeterminant() < 0) {
  28618. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28619. }
  28620. }
  28621. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28622. if (this._effectiveMaterial.forceDepthWrite) {
  28623. engine.setDepthWrite(true);
  28624. }
  28625. // Bind
  28626. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28627. if (!hardwareInstancedRendering) {
  28628. this._bind(subMesh, effect, fillMode);
  28629. }
  28630. var world = this.getWorldMatrix();
  28631. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28632. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28633. }
  28634. else {
  28635. this._effectiveMaterial.bind(world, this);
  28636. }
  28637. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28638. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28639. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28640. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28641. }
  28642. // Draw
  28643. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28644. // Unbind
  28645. this._effectiveMaterial.unbind();
  28646. // Outline - step 2
  28647. if (this.renderOutline && savedDepthWrite) {
  28648. engine.setDepthWrite(true);
  28649. engine.setColorWrite(false);
  28650. scene.getOutlineRenderer().render(subMesh, batch);
  28651. engine.setColorWrite(true);
  28652. }
  28653. // Overlay
  28654. if (this.renderOverlay) {
  28655. var currentMode = engine.getAlphaMode();
  28656. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28657. scene.getOutlineRenderer().render(subMesh, batch, true);
  28658. engine.setAlphaMode(currentMode);
  28659. }
  28660. this.onAfterRenderObservable.notifyObservers(this);
  28661. return this;
  28662. };
  28663. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28664. if (isInstance && effectiveMaterial) {
  28665. effectiveMaterial.bindOnlyWorldMatrix(world);
  28666. }
  28667. };
  28668. /**
  28669. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28670. */
  28671. Mesh.prototype.getEmittedParticleSystems = function () {
  28672. var results = new Array();
  28673. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28674. var particleSystem = this.getScene().particleSystems[index];
  28675. if (particleSystem.emitter === this) {
  28676. results.push(particleSystem);
  28677. }
  28678. }
  28679. return results;
  28680. };
  28681. /**
  28682. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28683. */
  28684. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28685. var results = new Array();
  28686. var descendants = this.getDescendants();
  28687. descendants.push(this);
  28688. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28689. var particleSystem = this.getScene().particleSystems[index];
  28690. var emitter = particleSystem.emitter;
  28691. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28692. results.push(particleSystem);
  28693. }
  28694. }
  28695. return results;
  28696. };
  28697. Mesh.prototype._checkDelayState = function () {
  28698. var scene = this.getScene();
  28699. if (this._geometry) {
  28700. this._geometry.load(scene);
  28701. }
  28702. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28704. this._queueLoad(scene);
  28705. }
  28706. return this;
  28707. };
  28708. Mesh.prototype._queueLoad = function (scene) {
  28709. var _this = this;
  28710. scene._addPendingData(this);
  28711. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28712. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28713. if (data instanceof ArrayBuffer) {
  28714. _this._delayLoadingFunction(data, _this);
  28715. }
  28716. else {
  28717. _this._delayLoadingFunction(JSON.parse(data), _this);
  28718. }
  28719. _this.instances.forEach(function (instance) {
  28720. instance._syncSubMeshes();
  28721. });
  28722. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28723. scene._removePendingData(_this);
  28724. }, function () { }, scene.database, getBinaryData);
  28725. return this;
  28726. };
  28727. /**
  28728. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28729. */
  28730. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28731. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28732. return false;
  28733. }
  28734. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28735. return false;
  28736. }
  28737. this._checkDelayState();
  28738. return true;
  28739. };
  28740. /**
  28741. * Sets the mesh material by the material or multiMaterial `id` property.
  28742. * The material `id` is a string identifying the material or the multiMaterial.
  28743. * This method returns the Mesh.
  28744. */
  28745. Mesh.prototype.setMaterialByID = function (id) {
  28746. var materials = this.getScene().materials;
  28747. var index;
  28748. for (index = materials.length - 1; index > -1; index--) {
  28749. if (materials[index].id === id) {
  28750. this.material = materials[index];
  28751. return this;
  28752. }
  28753. }
  28754. // Multi
  28755. var multiMaterials = this.getScene().multiMaterials;
  28756. for (index = multiMaterials.length - 1; index > -1; index--) {
  28757. if (multiMaterials[index].id === id) {
  28758. this.material = multiMaterials[index];
  28759. return this;
  28760. }
  28761. }
  28762. return this;
  28763. };
  28764. /**
  28765. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28766. */
  28767. Mesh.prototype.getAnimatables = function () {
  28768. var results = new Array();
  28769. if (this.material) {
  28770. results.push(this.material);
  28771. }
  28772. if (this.skeleton) {
  28773. results.push(this.skeleton);
  28774. }
  28775. return results;
  28776. };
  28777. /**
  28778. * Modifies the mesh geometry according to the passed transformation matrix.
  28779. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28780. * The mesh normals are modified accordingly the same transformation.
  28781. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28782. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28783. * Returns the Mesh.
  28784. */
  28785. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28786. // Position
  28787. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28788. return this;
  28789. }
  28790. var submeshes = this.subMeshes.splice(0);
  28791. this._resetPointsArrayCache();
  28792. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28793. var temp = new Array();
  28794. var index;
  28795. for (index = 0; index < data.length; index += 3) {
  28796. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28797. }
  28798. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28799. // Normals
  28800. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28801. return this;
  28802. }
  28803. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28804. temp = [];
  28805. for (index = 0; index < data.length; index += 3) {
  28806. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28807. }
  28808. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28809. // flip faces?
  28810. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28811. this.flipFaces();
  28812. }
  28813. // Restore submeshes
  28814. this.releaseSubMeshes();
  28815. this.subMeshes = submeshes;
  28816. return this;
  28817. };
  28818. /**
  28819. * Modifies the mesh geometry according to its own current World Matrix.
  28820. * The mesh World Matrix is then reset.
  28821. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28822. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28823. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28824. * Returns the Mesh.
  28825. */
  28826. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28827. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28828. this.scaling.copyFromFloats(1, 1, 1);
  28829. this.position.copyFromFloats(0, 0, 0);
  28830. this.rotation.copyFromFloats(0, 0, 0);
  28831. //only if quaternion is already set
  28832. if (this.rotationQuaternion) {
  28833. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28834. }
  28835. this._worldMatrix = BABYLON.Matrix.Identity();
  28836. return this;
  28837. };
  28838. Object.defineProperty(Mesh.prototype, "_positions", {
  28839. // Cache
  28840. get: function () {
  28841. if (this._geometry) {
  28842. return this._geometry._positions;
  28843. }
  28844. return null;
  28845. },
  28846. enumerable: true,
  28847. configurable: true
  28848. });
  28849. Mesh.prototype._resetPointsArrayCache = function () {
  28850. if (this._geometry) {
  28851. this._geometry._resetPointsArrayCache();
  28852. }
  28853. return this;
  28854. };
  28855. Mesh.prototype._generatePointsArray = function () {
  28856. if (this._geometry) {
  28857. return this._geometry._generatePointsArray();
  28858. }
  28859. return false;
  28860. };
  28861. /**
  28862. * Returns a new Mesh object generated from the current mesh properties.
  28863. * This method must not get confused with createInstance().
  28864. * The parameter `name` is a string, the name given to the new mesh.
  28865. * The optional parameter `newParent` can be any Node object (default `null`).
  28866. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28867. * 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.
  28868. */
  28869. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28870. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28871. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28872. };
  28873. /**
  28874. * Releases resources associated with this mesh.
  28875. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28876. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28877. */
  28878. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28879. var _this = this;
  28880. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28881. this.morphTargetManager = null;
  28882. if (this._geometry) {
  28883. this._geometry.releaseForMesh(this, true);
  28884. }
  28885. // Sources
  28886. var meshes = this.getScene().meshes;
  28887. meshes.forEach(function (abstractMesh) {
  28888. var mesh = abstractMesh;
  28889. if (mesh._source && mesh._source === _this) {
  28890. mesh._source = null;
  28891. }
  28892. });
  28893. this._source = null;
  28894. // Instances
  28895. if (this._instancesBuffer) {
  28896. this._instancesBuffer.dispose();
  28897. this._instancesBuffer = null;
  28898. }
  28899. while (this.instances.length) {
  28900. this.instances[0].dispose();
  28901. }
  28902. // Effect layers.
  28903. var effectLayers = this.getScene().effectLayers;
  28904. for (var i = 0; i < effectLayers.length; i++) {
  28905. var effectLayer = effectLayers[i];
  28906. if (effectLayer) {
  28907. effectLayer._disposeMesh(this);
  28908. }
  28909. }
  28910. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28911. };
  28912. /**
  28913. * Modifies the mesh geometry according to a displacement map.
  28914. * 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.
  28915. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28916. * This method returns nothing.
  28917. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28918. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28919. * 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.
  28920. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28921. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28922. *
  28923. * Returns the Mesh.
  28924. */
  28925. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28926. var _this = this;
  28927. var scene = this.getScene();
  28928. var onload = function (img) {
  28929. // Getting height map data
  28930. var canvas = document.createElement("canvas");
  28931. var context = canvas.getContext("2d");
  28932. var heightMapWidth = img.width;
  28933. var heightMapHeight = img.height;
  28934. canvas.width = heightMapWidth;
  28935. canvas.height = heightMapHeight;
  28936. context.drawImage(img, 0, 0);
  28937. // Create VertexData from map data
  28938. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28939. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28940. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28941. //execute success callback, if set
  28942. if (onSuccess) {
  28943. onSuccess(_this);
  28944. }
  28945. };
  28946. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28947. return this;
  28948. };
  28949. /**
  28950. * Modifies the mesh geometry according to a displacementMap buffer.
  28951. * 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.
  28952. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28953. * This method returns nothing.
  28954. * 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.
  28955. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28956. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28957. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28958. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28959. *
  28960. * Returns the Mesh.
  28961. */
  28962. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28963. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28964. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28965. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28966. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28967. return this;
  28968. }
  28969. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28970. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28971. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28972. var position = BABYLON.Vector3.Zero();
  28973. var normal = BABYLON.Vector3.Zero();
  28974. var uv = BABYLON.Vector2.Zero();
  28975. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28976. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28977. for (var index = 0; index < positions.length; index += 3) {
  28978. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28979. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28980. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28981. // Compute height
  28982. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28983. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28984. var pos = (u + v * heightMapWidth) * 4;
  28985. var r = buffer[pos] / 255.0;
  28986. var g = buffer[pos + 1] / 255.0;
  28987. var b = buffer[pos + 2] / 255.0;
  28988. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28989. normal.normalize();
  28990. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28991. position = position.add(normal);
  28992. position.toArray(positions, index);
  28993. }
  28994. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28995. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28996. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28997. return this;
  28998. };
  28999. /**
  29000. * Modify the mesh to get a flat shading rendering.
  29001. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29002. * This method returns the Mesh.
  29003. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29004. */
  29005. Mesh.prototype.convertToFlatShadedMesh = function () {
  29006. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29007. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29008. var kinds = this.getVerticesDataKinds();
  29009. var vbs = {};
  29010. var data = {};
  29011. var newdata = {};
  29012. var updatableNormals = false;
  29013. var kindIndex;
  29014. var kind;
  29015. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29016. kind = kinds[kindIndex];
  29017. var vertexBuffer = this.getVertexBuffer(kind);
  29018. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29019. updatableNormals = vertexBuffer.isUpdatable();
  29020. kinds.splice(kindIndex, 1);
  29021. kindIndex--;
  29022. continue;
  29023. }
  29024. vbs[kind] = vertexBuffer;
  29025. data[kind] = vbs[kind].getData();
  29026. newdata[kind] = [];
  29027. }
  29028. // Save previous submeshes
  29029. var previousSubmeshes = this.subMeshes.slice(0);
  29030. var indices = this.getIndices();
  29031. var totalIndices = this.getTotalIndices();
  29032. // Generating unique vertices per face
  29033. var index;
  29034. for (index = 0; index < totalIndices; index++) {
  29035. var vertexIndex = indices[index];
  29036. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29037. kind = kinds[kindIndex];
  29038. var stride = vbs[kind].getStrideSize();
  29039. for (var offset = 0; offset < stride; offset++) {
  29040. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29041. }
  29042. }
  29043. }
  29044. // Updating faces & normal
  29045. var normals = [];
  29046. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29047. for (index = 0; index < totalIndices; index += 3) {
  29048. indices[index] = index;
  29049. indices[index + 1] = index + 1;
  29050. indices[index + 2] = index + 2;
  29051. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29052. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29053. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29054. var p1p2 = p1.subtract(p2);
  29055. var p3p2 = p3.subtract(p2);
  29056. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29057. // Store same normals for every vertex
  29058. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29059. normals.push(normal.x);
  29060. normals.push(normal.y);
  29061. normals.push(normal.z);
  29062. }
  29063. }
  29064. this.setIndices(indices);
  29065. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29066. // Updating vertex buffers
  29067. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29068. kind = kinds[kindIndex];
  29069. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29070. }
  29071. // Updating submeshes
  29072. this.releaseSubMeshes();
  29073. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29074. var previousOne = previousSubmeshes[submeshIndex];
  29075. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29076. }
  29077. this.synchronizeInstances();
  29078. return this;
  29079. };
  29080. /**
  29081. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29082. * In other words, more vertices, no more indices and a single bigger VBO.
  29083. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29084. * Returns the Mesh.
  29085. */
  29086. Mesh.prototype.convertToUnIndexedMesh = function () {
  29087. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29088. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29089. var kinds = this.getVerticesDataKinds();
  29090. var vbs = {};
  29091. var data = {};
  29092. var newdata = {};
  29093. var kindIndex;
  29094. var kind;
  29095. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29096. kind = kinds[kindIndex];
  29097. var vertexBuffer = this.getVertexBuffer(kind);
  29098. vbs[kind] = vertexBuffer;
  29099. data[kind] = vbs[kind].getData();
  29100. newdata[kind] = [];
  29101. }
  29102. // Save previous submeshes
  29103. var previousSubmeshes = this.subMeshes.slice(0);
  29104. var indices = this.getIndices();
  29105. var totalIndices = this.getTotalIndices();
  29106. // Generating unique vertices per face
  29107. var index;
  29108. for (index = 0; index < totalIndices; index++) {
  29109. var vertexIndex = indices[index];
  29110. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29111. kind = kinds[kindIndex];
  29112. var stride = vbs[kind].getStrideSize();
  29113. for (var offset = 0; offset < stride; offset++) {
  29114. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29115. }
  29116. }
  29117. }
  29118. // Updating indices
  29119. for (index = 0; index < totalIndices; index += 3) {
  29120. indices[index] = index;
  29121. indices[index + 1] = index + 1;
  29122. indices[index + 2] = index + 2;
  29123. }
  29124. this.setIndices(indices);
  29125. // Updating vertex buffers
  29126. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29127. kind = kinds[kindIndex];
  29128. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29129. }
  29130. // Updating submeshes
  29131. this.releaseSubMeshes();
  29132. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29133. var previousOne = previousSubmeshes[submeshIndex];
  29134. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29135. }
  29136. this._unIndexed = true;
  29137. this.synchronizeInstances();
  29138. return this;
  29139. };
  29140. /**
  29141. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29142. * This method returns the Mesh.
  29143. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29144. */
  29145. Mesh.prototype.flipFaces = function (flipNormals) {
  29146. if (flipNormals === void 0) { flipNormals = false; }
  29147. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29148. var i;
  29149. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29150. for (i = 0; i < vertex_data.normals.length; i++) {
  29151. vertex_data.normals[i] *= -1;
  29152. }
  29153. }
  29154. if (vertex_data.indices) {
  29155. var temp;
  29156. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29157. // reassign indices
  29158. temp = vertex_data.indices[i + 1];
  29159. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29160. vertex_data.indices[i + 2] = temp;
  29161. }
  29162. }
  29163. vertex_data.applyToMesh(this);
  29164. return this;
  29165. };
  29166. // Instances
  29167. /**
  29168. * Creates a new InstancedMesh object from the mesh model.
  29169. * An instance shares the same properties and the same material than its model.
  29170. * Only these properties of each instance can then be set individually :
  29171. * - position
  29172. * - rotation
  29173. * - rotationQuaternion
  29174. * - setPivotMatrix
  29175. * - scaling
  29176. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29177. * Warning : this method is not supported for Line mesh and LineSystem
  29178. */
  29179. Mesh.prototype.createInstance = function (name) {
  29180. return new BABYLON.InstancedMesh(name, this);
  29181. };
  29182. /**
  29183. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29184. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29185. * This method returns the Mesh.
  29186. */
  29187. Mesh.prototype.synchronizeInstances = function () {
  29188. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29189. var instance = this.instances[instanceIndex];
  29190. instance._syncSubMeshes();
  29191. }
  29192. return this;
  29193. };
  29194. /**
  29195. * Simplify the mesh according to the given array of settings.
  29196. * Function will return immediately and will simplify async. It returns the Mesh.
  29197. * @param settings a collection of simplification settings.
  29198. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29199. * @param type the type of simplification to run.
  29200. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29201. */
  29202. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29203. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29204. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29205. this.getScene().simplificationQueue.addTask({
  29206. settings: settings,
  29207. parallelProcessing: parallelProcessing,
  29208. mesh: this,
  29209. simplificationType: simplificationType,
  29210. successCallback: successCallback
  29211. });
  29212. return this;
  29213. };
  29214. /**
  29215. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29216. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29217. * This should be used together with the simplification to avoid disappearing triangles.
  29218. * Returns the Mesh.
  29219. * @param successCallback an optional success callback to be called after the optimization finished.
  29220. */
  29221. Mesh.prototype.optimizeIndices = function (successCallback) {
  29222. var _this = this;
  29223. var indices = this.getIndices();
  29224. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29225. if (!positions || !indices) {
  29226. return this;
  29227. }
  29228. var vectorPositions = new Array();
  29229. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29230. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29231. }
  29232. var dupes = new Array();
  29233. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29234. var realPos = vectorPositions.length - 1 - iteration;
  29235. var testedPosition = vectorPositions[realPos];
  29236. for (var j = 0; j < realPos; ++j) {
  29237. var againstPosition = vectorPositions[j];
  29238. if (testedPosition.equals(againstPosition)) {
  29239. dupes[realPos] = j;
  29240. break;
  29241. }
  29242. }
  29243. }, function () {
  29244. for (var i = 0; i < indices.length; ++i) {
  29245. indices[i] = dupes[indices[i]] || indices[i];
  29246. }
  29247. //indices are now reordered
  29248. var originalSubMeshes = _this.subMeshes.slice(0);
  29249. _this.setIndices(indices);
  29250. _this.subMeshes = originalSubMeshes;
  29251. if (successCallback) {
  29252. successCallback(_this);
  29253. }
  29254. });
  29255. return this;
  29256. };
  29257. Mesh.prototype.serialize = function (serializationObject) {
  29258. serializationObject.name = this.name;
  29259. serializationObject.id = this.id;
  29260. serializationObject.type = this.getClassName();
  29261. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29262. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29263. }
  29264. serializationObject.position = this.position.asArray();
  29265. if (this.rotationQuaternion) {
  29266. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29267. }
  29268. else if (this.rotation) {
  29269. serializationObject.rotation = this.rotation.asArray();
  29270. }
  29271. serializationObject.scaling = this.scaling.asArray();
  29272. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29273. serializationObject.isEnabled = this.isEnabled(false);
  29274. serializationObject.isVisible = this.isVisible;
  29275. serializationObject.infiniteDistance = this.infiniteDistance;
  29276. serializationObject.pickable = this.isPickable;
  29277. serializationObject.receiveShadows = this.receiveShadows;
  29278. serializationObject.billboardMode = this.billboardMode;
  29279. serializationObject.visibility = this.visibility;
  29280. serializationObject.checkCollisions = this.checkCollisions;
  29281. serializationObject.isBlocker = this.isBlocker;
  29282. // Parent
  29283. if (this.parent) {
  29284. serializationObject.parentId = this.parent.id;
  29285. }
  29286. // Geometry
  29287. serializationObject.isUnIndexed = this.isUnIndexed;
  29288. var geometry = this._geometry;
  29289. if (geometry) {
  29290. var geometryId = geometry.id;
  29291. serializationObject.geometryId = geometryId;
  29292. // SubMeshes
  29293. serializationObject.subMeshes = [];
  29294. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29295. var subMesh = this.subMeshes[subIndex];
  29296. serializationObject.subMeshes.push({
  29297. materialIndex: subMesh.materialIndex,
  29298. verticesStart: subMesh.verticesStart,
  29299. verticesCount: subMesh.verticesCount,
  29300. indexStart: subMesh.indexStart,
  29301. indexCount: subMesh.indexCount
  29302. });
  29303. }
  29304. }
  29305. // Material
  29306. if (this.material) {
  29307. serializationObject.materialId = this.material.id;
  29308. }
  29309. else {
  29310. this.material = null;
  29311. }
  29312. // Morph targets
  29313. if (this.morphTargetManager) {
  29314. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29315. }
  29316. // Skeleton
  29317. if (this.skeleton) {
  29318. serializationObject.skeletonId = this.skeleton.id;
  29319. }
  29320. // Physics
  29321. //TODO implement correct serialization for physics impostors.
  29322. var impostor = this.getPhysicsImpostor();
  29323. if (impostor) {
  29324. serializationObject.physicsMass = impostor.getParam("mass");
  29325. serializationObject.physicsFriction = impostor.getParam("friction");
  29326. serializationObject.physicsRestitution = impostor.getParam("mass");
  29327. serializationObject.physicsImpostor = impostor.type;
  29328. }
  29329. // Metadata
  29330. if (this.metadata) {
  29331. serializationObject.metadata = this.metadata;
  29332. }
  29333. // Instances
  29334. serializationObject.instances = [];
  29335. for (var index = 0; index < this.instances.length; index++) {
  29336. var instance = this.instances[index];
  29337. var serializationInstance = {
  29338. name: instance.name,
  29339. id: instance.id,
  29340. position: instance.position.asArray(),
  29341. scaling: instance.scaling.asArray()
  29342. };
  29343. if (instance.rotationQuaternion) {
  29344. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29345. }
  29346. else if (instance.rotation) {
  29347. serializationInstance.rotation = instance.rotation.asArray();
  29348. }
  29349. serializationObject.instances.push(serializationInstance);
  29350. // Animations
  29351. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29352. serializationInstance.ranges = instance.serializeAnimationRanges();
  29353. }
  29354. //
  29355. // Animations
  29356. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29357. serializationObject.ranges = this.serializeAnimationRanges();
  29358. // Layer mask
  29359. serializationObject.layerMask = this.layerMask;
  29360. // Alpha
  29361. serializationObject.alphaIndex = this.alphaIndex;
  29362. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29363. // Overlay
  29364. serializationObject.overlayAlpha = this.overlayAlpha;
  29365. serializationObject.overlayColor = this.overlayColor.asArray();
  29366. serializationObject.renderOverlay = this.renderOverlay;
  29367. // Fog
  29368. serializationObject.applyFog = this.applyFog;
  29369. // Action Manager
  29370. if (this.actionManager) {
  29371. serializationObject.actions = this.actionManager.serialize(this.name);
  29372. }
  29373. };
  29374. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29375. if (!this.geometry) {
  29376. return;
  29377. }
  29378. this._markSubMeshesAsAttributesDirty();
  29379. var morphTargetManager = this._morphTargetManager;
  29380. if (morphTargetManager && morphTargetManager.vertexCount) {
  29381. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29382. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29383. this.morphTargetManager = null;
  29384. return;
  29385. }
  29386. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29387. var morphTarget = morphTargetManager.getActiveTarget(index);
  29388. var positions = morphTarget.getPositions();
  29389. if (!positions) {
  29390. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29391. return;
  29392. }
  29393. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29394. var normals = morphTarget.getNormals();
  29395. if (normals) {
  29396. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29397. }
  29398. var tangents = morphTarget.getTangents();
  29399. if (tangents) {
  29400. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29401. }
  29402. }
  29403. }
  29404. else {
  29405. var index = 0;
  29406. // Positions
  29407. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29408. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29409. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29410. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29411. }
  29412. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29413. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29414. }
  29415. index++;
  29416. }
  29417. }
  29418. };
  29419. // Statics
  29420. /**
  29421. * Returns a new Mesh object parsed from the source provided.
  29422. * The parameter `parsedMesh` is the source.
  29423. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29424. */
  29425. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29426. var mesh;
  29427. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29428. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29429. }
  29430. else {
  29431. mesh = new Mesh(parsedMesh.name, scene);
  29432. }
  29433. mesh.id = parsedMesh.id;
  29434. if (BABYLON.Tags) {
  29435. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29436. }
  29437. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29438. if (parsedMesh.metadata !== undefined) {
  29439. mesh.metadata = parsedMesh.metadata;
  29440. }
  29441. if (parsedMesh.rotationQuaternion) {
  29442. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29443. }
  29444. else if (parsedMesh.rotation) {
  29445. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29446. }
  29447. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29448. if (parsedMesh.localMatrix) {
  29449. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29450. }
  29451. else if (parsedMesh.pivotMatrix) {
  29452. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29453. }
  29454. mesh.setEnabled(parsedMesh.isEnabled);
  29455. mesh.isVisible = parsedMesh.isVisible;
  29456. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29457. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29458. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29459. if (parsedMesh.applyFog !== undefined) {
  29460. mesh.applyFog = parsedMesh.applyFog;
  29461. }
  29462. if (parsedMesh.pickable !== undefined) {
  29463. mesh.isPickable = parsedMesh.pickable;
  29464. }
  29465. if (parsedMesh.alphaIndex !== undefined) {
  29466. mesh.alphaIndex = parsedMesh.alphaIndex;
  29467. }
  29468. mesh.receiveShadows = parsedMesh.receiveShadows;
  29469. mesh.billboardMode = parsedMesh.billboardMode;
  29470. if (parsedMesh.visibility !== undefined) {
  29471. mesh.visibility = parsedMesh.visibility;
  29472. }
  29473. mesh.checkCollisions = parsedMesh.checkCollisions;
  29474. if (parsedMesh.isBlocker !== undefined) {
  29475. mesh.isBlocker = parsedMesh.isBlocker;
  29476. }
  29477. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29478. // freezeWorldMatrix
  29479. if (parsedMesh.freezeWorldMatrix) {
  29480. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29481. }
  29482. // Parent
  29483. if (parsedMesh.parentId) {
  29484. mesh._waitingParentId = parsedMesh.parentId;
  29485. }
  29486. // Actions
  29487. if (parsedMesh.actions !== undefined) {
  29488. mesh._waitingActions = parsedMesh.actions;
  29489. }
  29490. // Overlay
  29491. if (parsedMesh.overlayAlpha !== undefined) {
  29492. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29493. }
  29494. if (parsedMesh.overlayColor !== undefined) {
  29495. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29496. }
  29497. if (parsedMesh.renderOverlay !== undefined) {
  29498. mesh.renderOverlay = parsedMesh.renderOverlay;
  29499. }
  29500. // Geometry
  29501. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29502. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29503. if (parsedMesh.delayLoadingFile) {
  29504. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29505. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29506. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29507. if (parsedMesh._binaryInfo) {
  29508. mesh._binaryInfo = parsedMesh._binaryInfo;
  29509. }
  29510. mesh._delayInfo = [];
  29511. if (parsedMesh.hasUVs) {
  29512. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29513. }
  29514. if (parsedMesh.hasUVs2) {
  29515. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29516. }
  29517. if (parsedMesh.hasUVs3) {
  29518. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29519. }
  29520. if (parsedMesh.hasUVs4) {
  29521. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29522. }
  29523. if (parsedMesh.hasUVs5) {
  29524. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29525. }
  29526. if (parsedMesh.hasUVs6) {
  29527. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29528. }
  29529. if (parsedMesh.hasColors) {
  29530. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29531. }
  29532. if (parsedMesh.hasMatricesIndices) {
  29533. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29534. }
  29535. if (parsedMesh.hasMatricesWeights) {
  29536. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29537. }
  29538. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29539. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29540. mesh._checkDelayState();
  29541. }
  29542. }
  29543. else {
  29544. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29545. }
  29546. // Material
  29547. if (parsedMesh.materialId) {
  29548. mesh.setMaterialByID(parsedMesh.materialId);
  29549. }
  29550. else {
  29551. mesh.material = null;
  29552. }
  29553. // Morph targets
  29554. if (parsedMesh.morphTargetManagerId > -1) {
  29555. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29556. }
  29557. // Skeleton
  29558. if (parsedMesh.skeletonId > -1) {
  29559. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29560. if (parsedMesh.numBoneInfluencers) {
  29561. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29562. }
  29563. }
  29564. // Animations
  29565. if (parsedMesh.animations) {
  29566. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29567. var parsedAnimation = parsedMesh.animations[animationIndex];
  29568. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29569. }
  29570. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29571. }
  29572. if (parsedMesh.autoAnimate) {
  29573. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29574. }
  29575. // Layer Mask
  29576. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29577. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29578. }
  29579. else {
  29580. mesh.layerMask = 0x0FFFFFFF;
  29581. }
  29582. // Physics
  29583. if (parsedMesh.physicsImpostor) {
  29584. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29585. mass: parsedMesh.physicsMass,
  29586. friction: parsedMesh.physicsFriction,
  29587. restitution: parsedMesh.physicsRestitution
  29588. }, scene);
  29589. }
  29590. // Instances
  29591. if (parsedMesh.instances) {
  29592. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29593. var parsedInstance = parsedMesh.instances[index];
  29594. var instance = mesh.createInstance(parsedInstance.name);
  29595. if (parsedInstance.id) {
  29596. instance.id = parsedInstance.id;
  29597. }
  29598. if (BABYLON.Tags) {
  29599. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29600. }
  29601. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29602. if (parsedInstance.parentId) {
  29603. instance._waitingParentId = parsedInstance.parentId;
  29604. }
  29605. if (parsedInstance.rotationQuaternion) {
  29606. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29607. }
  29608. else if (parsedInstance.rotation) {
  29609. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29610. }
  29611. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29612. instance.checkCollisions = mesh.checkCollisions;
  29613. if (parsedMesh.animations) {
  29614. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29615. parsedAnimation = parsedMesh.animations[animationIndex];
  29616. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29617. }
  29618. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29619. }
  29620. }
  29621. }
  29622. return mesh;
  29623. };
  29624. /**
  29625. * Creates a ribbon mesh.
  29626. * Please consider using the same method from the MeshBuilder class instead.
  29627. * 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.
  29628. *
  29629. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29630. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29631. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29632. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29633. * 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.
  29634. * 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.
  29635. * 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
  29636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29639. */
  29640. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29641. if (closeArray === void 0) { closeArray = false; }
  29642. if (updatable === void 0) { updatable = false; }
  29643. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29644. pathArray: pathArray,
  29645. closeArray: closeArray,
  29646. closePath: closePath,
  29647. offset: offset,
  29648. updatable: updatable,
  29649. sideOrientation: sideOrientation,
  29650. instance: instance
  29651. }, scene);
  29652. };
  29653. /**
  29654. * Creates a plane polygonal mesh. By default, this is a disc.
  29655. * Please consider using the same method from the MeshBuilder class instead.
  29656. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29657. * 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.
  29658. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29659. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29660. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29661. */
  29662. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29663. if (scene === void 0) { scene = null; }
  29664. var options = {
  29665. radius: radius,
  29666. tessellation: tessellation,
  29667. sideOrientation: sideOrientation,
  29668. updatable: updatable
  29669. };
  29670. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29671. };
  29672. /**
  29673. * Creates a box mesh.
  29674. * Please consider using the same method from the MeshBuilder class instead.
  29675. * The parameter `size` sets the size (float) of each box side (default 1).
  29676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29679. */
  29680. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29681. if (scene === void 0) { scene = null; }
  29682. var options = {
  29683. size: size,
  29684. sideOrientation: sideOrientation,
  29685. updatable: updatable
  29686. };
  29687. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29688. };
  29689. /**
  29690. * Creates a sphere mesh.
  29691. * Please consider using the same method from the MeshBuilder class instead.
  29692. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29693. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29695. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29697. */
  29698. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29699. var options = {
  29700. segments: segments,
  29701. diameterX: diameter,
  29702. diameterY: diameter,
  29703. diameterZ: diameter,
  29704. sideOrientation: sideOrientation,
  29705. updatable: updatable
  29706. };
  29707. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29708. };
  29709. /**
  29710. * Creates a cylinder or a cone mesh.
  29711. * Please consider using the same method from the MeshBuilder class instead.
  29712. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29713. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29714. * 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.
  29715. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29716. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29717. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29720. */
  29721. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29722. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29723. if (scene !== undefined) {
  29724. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29725. updatable = scene;
  29726. }
  29727. scene = subdivisions;
  29728. subdivisions = 1;
  29729. }
  29730. var options = {
  29731. height: height,
  29732. diameterTop: diameterTop,
  29733. diameterBottom: diameterBottom,
  29734. tessellation: tessellation,
  29735. subdivisions: subdivisions,
  29736. sideOrientation: sideOrientation,
  29737. updatable: updatable
  29738. };
  29739. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29740. };
  29741. // Torus (Code from SharpDX.org)
  29742. /**
  29743. * Creates a torus mesh.
  29744. * Please consider using the same method from the MeshBuilder class instead.
  29745. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29746. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29747. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29749. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29751. */
  29752. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29753. var options = {
  29754. diameter: diameter,
  29755. thickness: thickness,
  29756. tessellation: tessellation,
  29757. sideOrientation: sideOrientation,
  29758. updatable: updatable
  29759. };
  29760. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29761. };
  29762. /**
  29763. * Creates a torus knot mesh.
  29764. * Please consider using the same method from the MeshBuilder class instead.
  29765. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29766. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29767. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29768. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29769. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29770. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29772. */
  29773. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29774. var options = {
  29775. radius: radius,
  29776. tube: tube,
  29777. radialSegments: radialSegments,
  29778. tubularSegments: tubularSegments,
  29779. p: p,
  29780. q: q,
  29781. sideOrientation: sideOrientation,
  29782. updatable: updatable
  29783. };
  29784. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29785. };
  29786. /**
  29787. * Creates a line mesh.
  29788. * Please consider using the same method from the MeshBuilder class instead.
  29789. * 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.
  29790. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29791. * The parameter `points` is an array successive Vector3.
  29792. * 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
  29793. * When updating an instance, remember that only point positions can change, not the number of points.
  29794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29795. */
  29796. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29797. if (scene === void 0) { scene = null; }
  29798. if (updatable === void 0) { updatable = false; }
  29799. if (instance === void 0) { instance = null; }
  29800. var options = {
  29801. points: points,
  29802. updatable: updatable,
  29803. instance: instance
  29804. };
  29805. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29806. };
  29807. /**
  29808. * Creates a dashed line mesh.
  29809. * Please consider using the same method from the MeshBuilder class instead.
  29810. * 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.
  29811. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29812. * The parameter `points` is an array successive Vector3.
  29813. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29814. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29815. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29816. * 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
  29817. * When updating an instance, remember that only point positions can change, not the number of points.
  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.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29821. if (scene === void 0) { scene = null; }
  29822. var options = {
  29823. points: points,
  29824. dashSize: dashSize,
  29825. gapSize: gapSize,
  29826. dashNb: dashNb,
  29827. updatable: updatable,
  29828. instance: instance
  29829. };
  29830. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29831. };
  29832. /**
  29833. * Creates a polygon mesh.
  29834. * Please consider using the same method from the MeshBuilder class instead.
  29835. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29836. * 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.
  29837. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  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. * Remember you can only change the shape positions, not their number when updating a polygon.
  29840. */
  29841. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29842. var options = {
  29843. shape: shape,
  29844. holes: holes,
  29845. updatable: updatable,
  29846. sideOrientation: sideOrientation
  29847. };
  29848. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29849. };
  29850. /**
  29851. * Creates an extruded polygon mesh, with depth in the Y direction.
  29852. * Please consider using the same method from the MeshBuilder class instead.
  29853. */
  29854. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29855. var options = {
  29856. shape: shape,
  29857. holes: holes,
  29858. depth: depth,
  29859. updatable: updatable,
  29860. sideOrientation: sideOrientation
  29861. };
  29862. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29863. };
  29864. /**
  29865. * Creates an extruded shape mesh.
  29866. * 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.
  29867. * Please consider using the same method from the MeshBuilder class instead.
  29868. *
  29869. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29870. * 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
  29871. * extruded along the Z axis.
  29872. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29873. * 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.
  29874. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29875. * 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
  29876. * 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
  29877. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29879. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29881. */
  29882. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29883. if (scene === void 0) { scene = null; }
  29884. var options = {
  29885. shape: shape,
  29886. path: path,
  29887. scale: scale,
  29888. rotation: rotation,
  29889. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29890. sideOrientation: sideOrientation,
  29891. instance: instance,
  29892. updatable: updatable
  29893. };
  29894. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29895. };
  29896. /**
  29897. * Creates an custom extruded shape mesh.
  29898. * 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.
  29899. * Please consider using the same method from the MeshBuilder class instead.
  29900. *
  29901. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29902. * 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
  29903. * extruded along the Z axis.
  29904. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29905. * 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
  29906. * and the distance of this point from the begining of the path :
  29907. * ```javascript
  29908. * var rotationFunction = function(i, distance) {
  29909. * // do things
  29910. * return rotationValue; }
  29911. * ```
  29912. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29913. * 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
  29914. * and the distance of this point from the begining of the path :
  29915. * ```javascript
  29916. * var scaleFunction = function(i, distance) {
  29917. * // do things
  29918. * return scaleValue;}
  29919. * ```
  29920. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29921. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29922. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29923. * 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
  29924. * 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
  29925. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29927. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29929. */
  29930. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29931. var options = {
  29932. shape: shape,
  29933. path: path,
  29934. scaleFunction: scaleFunction,
  29935. rotationFunction: rotationFunction,
  29936. ribbonCloseArray: ribbonCloseArray,
  29937. ribbonClosePath: ribbonClosePath,
  29938. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29939. sideOrientation: sideOrientation,
  29940. instance: instance,
  29941. updatable: updatable
  29942. };
  29943. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29944. };
  29945. /**
  29946. * Creates lathe mesh.
  29947. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29948. * Please consider using the same method from the MeshBuilder class instead.
  29949. * 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
  29950. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29951. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29952. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29956. */
  29957. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29958. var options = {
  29959. shape: shape,
  29960. radius: radius,
  29961. tessellation: tessellation,
  29962. sideOrientation: sideOrientation,
  29963. updatable: updatable
  29964. };
  29965. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29966. };
  29967. /**
  29968. * Creates a plane mesh.
  29969. * Please consider using the same method from the MeshBuilder class instead.
  29970. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29971. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29974. */
  29975. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29976. var options = {
  29977. size: size,
  29978. width: size,
  29979. height: size,
  29980. sideOrientation: sideOrientation,
  29981. updatable: updatable
  29982. };
  29983. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29984. };
  29985. /**
  29986. * Creates a ground mesh.
  29987. * Please consider using the same method from the MeshBuilder class instead.
  29988. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29989. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29991. */
  29992. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29993. var options = {
  29994. width: width,
  29995. height: height,
  29996. subdivisions: subdivisions,
  29997. updatable: updatable
  29998. };
  29999. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30000. };
  30001. /**
  30002. * Creates a tiled ground mesh.
  30003. * Please consider using the same method from the MeshBuilder class instead.
  30004. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30005. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30006. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30007. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30008. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30009. * numbers of subdivisions on the ground width and height of each tile.
  30010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30011. */
  30012. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30013. var options = {
  30014. xmin: xmin,
  30015. zmin: zmin,
  30016. xmax: xmax,
  30017. zmax: zmax,
  30018. subdivisions: subdivisions,
  30019. precision: precision,
  30020. updatable: updatable
  30021. };
  30022. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30023. };
  30024. /**
  30025. * Creates a ground mesh from a height map.
  30026. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30027. * Please consider using the same method from the MeshBuilder class instead.
  30028. * The parameter `url` sets the URL of the height map image resource.
  30029. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30030. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30031. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30032. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30033. * 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).
  30034. * This function is passed the newly built mesh :
  30035. * ```javascript
  30036. * function(mesh) { // do things
  30037. * return; }
  30038. * ```
  30039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30040. */
  30041. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30042. var options = {
  30043. width: width,
  30044. height: height,
  30045. subdivisions: subdivisions,
  30046. minHeight: minHeight,
  30047. maxHeight: maxHeight,
  30048. updatable: updatable,
  30049. onReady: onReady
  30050. };
  30051. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30052. };
  30053. /**
  30054. * Creates a tube mesh.
  30055. * 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.
  30056. * Please consider using the same method from the MeshBuilder class instead.
  30057. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30058. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30059. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30060. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30061. * 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.
  30062. * It must return a radius value (positive float) :
  30063. * ```javascript
  30064. * var radiusFunction = function(i, distance) {
  30065. * // do things
  30066. * return radius; }
  30067. * ```
  30068. * 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
  30069. * 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
  30070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30073. */
  30074. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30075. var options = {
  30076. path: path,
  30077. radius: radius,
  30078. tessellation: tessellation,
  30079. radiusFunction: radiusFunction,
  30080. arc: 1,
  30081. cap: cap,
  30082. updatable: updatable,
  30083. sideOrientation: sideOrientation,
  30084. instance: instance
  30085. };
  30086. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30087. };
  30088. /**
  30089. * Creates a polyhedron mesh.
  30090. * Please consider using the same method from the MeshBuilder class instead.
  30091. * 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
  30092. * to choose the wanted type.
  30093. * The parameter `size` (positive float, default 1) sets the polygon size.
  30094. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30095. * 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`.
  30096. * 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
  30097. * 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)`).
  30098. * 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
  30099. * 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.
  30100. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30101. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30103. */
  30104. Mesh.CreatePolyhedron = function (name, options, scene) {
  30105. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30106. };
  30107. /**
  30108. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30109. * Please consider using the same method from the MeshBuilder class instead.
  30110. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30111. * 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`).
  30112. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30113. * 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.
  30114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30117. */
  30118. Mesh.CreateIcoSphere = function (name, options, scene) {
  30119. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30120. };
  30121. /**
  30122. * Creates a decal mesh.
  30123. * Please consider using the same method from the MeshBuilder class instead.
  30124. * 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.
  30125. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30126. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30127. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30128. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30129. */
  30130. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30131. var options = {
  30132. position: position,
  30133. normal: normal,
  30134. size: size,
  30135. angle: angle
  30136. };
  30137. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30138. };
  30139. // Skeletons
  30140. /**
  30141. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30142. */
  30143. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30144. if (!this._sourcePositions) {
  30145. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30146. if (!source) {
  30147. return this._sourcePositions;
  30148. }
  30149. this._sourcePositions = new Float32Array(source);
  30150. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30151. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30152. }
  30153. }
  30154. return this._sourcePositions;
  30155. };
  30156. /**
  30157. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30158. */
  30159. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30160. if (!this._sourceNormals) {
  30161. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30162. if (!source) {
  30163. return this._sourceNormals;
  30164. }
  30165. this._sourceNormals = new Float32Array(source);
  30166. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30167. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30168. }
  30169. }
  30170. return this._sourceNormals;
  30171. };
  30172. /**
  30173. * Updates the vertex buffer by applying transformation from the bones.
  30174. * Returns the Mesh.
  30175. *
  30176. * @param {skeleton} skeleton to apply
  30177. */
  30178. Mesh.prototype.applySkeleton = function (skeleton) {
  30179. if (!this.geometry) {
  30180. return this;
  30181. }
  30182. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30183. return this;
  30184. }
  30185. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30186. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30187. return this;
  30188. }
  30189. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30190. return this;
  30191. }
  30192. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30193. return this;
  30194. }
  30195. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30196. return this;
  30197. }
  30198. if (!this._sourcePositions) {
  30199. var submeshes = this.subMeshes.slice();
  30200. this.setPositionsForCPUSkinning();
  30201. this.subMeshes = submeshes;
  30202. }
  30203. if (!this._sourceNormals) {
  30204. this.setNormalsForCPUSkinning();
  30205. }
  30206. // positionsData checks for not being Float32Array will only pass at most once
  30207. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30208. if (!positionsData) {
  30209. return this;
  30210. }
  30211. if (!(positionsData instanceof Float32Array)) {
  30212. positionsData = new Float32Array(positionsData);
  30213. }
  30214. // normalsData checks for not being Float32Array will only pass at most once
  30215. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30216. if (!normalsData) {
  30217. return this;
  30218. }
  30219. if (!(normalsData instanceof Float32Array)) {
  30220. normalsData = new Float32Array(normalsData);
  30221. }
  30222. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30223. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30224. if (!matricesWeightsData || !matricesIndicesData) {
  30225. return this;
  30226. }
  30227. var needExtras = this.numBoneInfluencers > 4;
  30228. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30229. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30230. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30231. var tempVector3 = BABYLON.Vector3.Zero();
  30232. var finalMatrix = new BABYLON.Matrix();
  30233. var tempMatrix = new BABYLON.Matrix();
  30234. var matWeightIdx = 0;
  30235. var inf;
  30236. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30237. var weight;
  30238. for (inf = 0; inf < 4; inf++) {
  30239. weight = matricesWeightsData[matWeightIdx + inf];
  30240. if (weight > 0) {
  30241. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30242. finalMatrix.addToSelf(tempMatrix);
  30243. }
  30244. else
  30245. break;
  30246. }
  30247. if (needExtras) {
  30248. for (inf = 0; inf < 4; inf++) {
  30249. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30250. if (weight > 0) {
  30251. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30252. finalMatrix.addToSelf(tempMatrix);
  30253. }
  30254. else
  30255. break;
  30256. }
  30257. }
  30258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30259. tempVector3.toArray(positionsData, index);
  30260. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30261. tempVector3.toArray(normalsData, index);
  30262. finalMatrix.reset();
  30263. }
  30264. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30265. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30266. return this;
  30267. };
  30268. // Tools
  30269. /**
  30270. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30271. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30272. */
  30273. Mesh.MinMax = function (meshes) {
  30274. var minVector = null;
  30275. var maxVector = null;
  30276. meshes.forEach(function (mesh, index, array) {
  30277. var boundingInfo = mesh.getBoundingInfo();
  30278. var boundingBox = boundingInfo.boundingBox;
  30279. if (!minVector || !maxVector) {
  30280. minVector = boundingBox.minimumWorld;
  30281. maxVector = boundingBox.maximumWorld;
  30282. }
  30283. else {
  30284. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30285. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30286. }
  30287. });
  30288. if (!minVector || !maxVector) {
  30289. return {
  30290. min: BABYLON.Vector3.Zero(),
  30291. max: BABYLON.Vector3.Zero()
  30292. };
  30293. }
  30294. return {
  30295. min: minVector,
  30296. max: maxVector
  30297. };
  30298. };
  30299. /**
  30300. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30301. */
  30302. Mesh.Center = function (meshesOrMinMaxVector) {
  30303. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30304. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30305. };
  30306. /**
  30307. * Merge the array of meshes into a single mesh for performance reasons.
  30308. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30309. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30310. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30311. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30312. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30313. */
  30314. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30315. if (disposeSource === void 0) { disposeSource = true; }
  30316. var index;
  30317. if (!allow32BitsIndices) {
  30318. var totalVertices = 0;
  30319. // Counting vertices
  30320. for (index = 0; index < meshes.length; index++) {
  30321. if (meshes[index]) {
  30322. totalVertices += meshes[index].getTotalVertices();
  30323. if (totalVertices > 65536) {
  30324. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30325. return null;
  30326. }
  30327. }
  30328. }
  30329. }
  30330. // Merge
  30331. var vertexData = null;
  30332. var otherVertexData;
  30333. var indiceArray = new Array();
  30334. var source = null;
  30335. for (index = 0; index < meshes.length; index++) {
  30336. if (meshes[index]) {
  30337. meshes[index].computeWorldMatrix(true);
  30338. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30339. otherVertexData.transform(meshes[index].getWorldMatrix());
  30340. if (vertexData) {
  30341. vertexData.merge(otherVertexData);
  30342. }
  30343. else {
  30344. vertexData = otherVertexData;
  30345. source = meshes[index];
  30346. }
  30347. if (subdivideWithSubMeshes) {
  30348. indiceArray.push(meshes[index].getTotalIndices());
  30349. }
  30350. }
  30351. }
  30352. source = source;
  30353. if (!meshSubclass) {
  30354. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30355. }
  30356. vertexData.applyToMesh(meshSubclass);
  30357. // Setting properties
  30358. meshSubclass.material = source.material;
  30359. meshSubclass.checkCollisions = source.checkCollisions;
  30360. // Cleaning
  30361. if (disposeSource) {
  30362. for (index = 0; index < meshes.length; index++) {
  30363. if (meshes[index]) {
  30364. meshes[index].dispose();
  30365. }
  30366. }
  30367. }
  30368. // Subdivide
  30369. if (subdivideWithSubMeshes) {
  30370. //-- Suppresions du submesh global
  30371. meshSubclass.releaseSubMeshes();
  30372. index = 0;
  30373. var offset = 0;
  30374. //-- aplique la subdivision en fonction du tableau d'indices
  30375. while (index < indiceArray.length) {
  30376. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30377. offset += indiceArray[index];
  30378. index++;
  30379. }
  30380. }
  30381. return meshSubclass;
  30382. };
  30383. // Consts
  30384. Mesh._FRONTSIDE = 0;
  30385. Mesh._BACKSIDE = 1;
  30386. Mesh._DOUBLESIDE = 2;
  30387. Mesh._DEFAULTSIDE = 0;
  30388. Mesh._NO_CAP = 0;
  30389. Mesh._CAP_START = 1;
  30390. Mesh._CAP_END = 2;
  30391. Mesh._CAP_ALL = 3;
  30392. return Mesh;
  30393. }(BABYLON.AbstractMesh));
  30394. BABYLON.Mesh = Mesh;
  30395. })(BABYLON || (BABYLON = {}));
  30396. //# sourceMappingURL=babylon.mesh.js.map
  30397. var BABYLON;
  30398. (function (BABYLON) {
  30399. var BaseSubMesh = /** @class */ (function () {
  30400. function BaseSubMesh() {
  30401. }
  30402. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30403. get: function () {
  30404. return this._materialEffect;
  30405. },
  30406. enumerable: true,
  30407. configurable: true
  30408. });
  30409. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30410. if (defines === void 0) { defines = null; }
  30411. if (this._materialEffect === effect) {
  30412. if (!effect) {
  30413. this._materialDefines = null;
  30414. }
  30415. return;
  30416. }
  30417. this._materialDefines = defines;
  30418. this._materialEffect = effect;
  30419. };
  30420. return BaseSubMesh;
  30421. }());
  30422. BABYLON.BaseSubMesh = BaseSubMesh;
  30423. var SubMesh = /** @class */ (function (_super) {
  30424. __extends(SubMesh, _super);
  30425. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30426. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30427. var _this = _super.call(this) || this;
  30428. _this.materialIndex = materialIndex;
  30429. _this.verticesStart = verticesStart;
  30430. _this.verticesCount = verticesCount;
  30431. _this.indexStart = indexStart;
  30432. _this.indexCount = indexCount;
  30433. _this._renderId = 0;
  30434. _this._mesh = mesh;
  30435. _this._renderingMesh = renderingMesh || mesh;
  30436. mesh.subMeshes.push(_this);
  30437. _this._trianglePlanes = [];
  30438. _this._id = mesh.subMeshes.length - 1;
  30439. if (createBoundingBox) {
  30440. _this.refreshBoundingInfo();
  30441. mesh.computeWorldMatrix(true);
  30442. }
  30443. return _this;
  30444. }
  30445. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30446. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30447. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30448. };
  30449. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30450. get: function () {
  30451. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30452. },
  30453. enumerable: true,
  30454. configurable: true
  30455. });
  30456. /**
  30457. * Returns the submesh BoudingInfo object.
  30458. */
  30459. SubMesh.prototype.getBoundingInfo = function () {
  30460. if (this.IsGlobal) {
  30461. return this._mesh.getBoundingInfo();
  30462. }
  30463. return this._boundingInfo;
  30464. };
  30465. /**
  30466. * Sets the submesh BoundingInfo.
  30467. * Return the SubMesh.
  30468. */
  30469. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30470. this._boundingInfo = boundingInfo;
  30471. return this;
  30472. };
  30473. /**
  30474. * Returns the mesh of the current submesh.
  30475. */
  30476. SubMesh.prototype.getMesh = function () {
  30477. return this._mesh;
  30478. };
  30479. /**
  30480. * Returns the rendering mesh of the submesh.
  30481. */
  30482. SubMesh.prototype.getRenderingMesh = function () {
  30483. return this._renderingMesh;
  30484. };
  30485. /**
  30486. * Returns the submesh material.
  30487. */
  30488. SubMesh.prototype.getMaterial = function () {
  30489. var rootMaterial = this._renderingMesh.material;
  30490. if (rootMaterial === null || rootMaterial === undefined) {
  30491. return this._mesh.getScene().defaultMaterial;
  30492. }
  30493. else if (rootMaterial.getSubMaterial) {
  30494. var multiMaterial = rootMaterial;
  30495. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30496. if (this._currentMaterial !== effectiveMaterial) {
  30497. this._currentMaterial = effectiveMaterial;
  30498. this._materialDefines = null;
  30499. }
  30500. return effectiveMaterial;
  30501. }
  30502. return rootMaterial;
  30503. };
  30504. // Methods
  30505. /**
  30506. * Sets a new updated BoundingInfo object to the submesh.
  30507. * Returns the SubMesh.
  30508. */
  30509. SubMesh.prototype.refreshBoundingInfo = function () {
  30510. this._lastColliderWorldVertices = null;
  30511. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30512. return this;
  30513. }
  30514. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30515. if (!data) {
  30516. this._boundingInfo = this._mesh.getBoundingInfo();
  30517. return this;
  30518. }
  30519. var indices = this._renderingMesh.getIndices();
  30520. var extend;
  30521. //is this the only submesh?
  30522. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30523. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30524. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30525. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30526. }
  30527. else {
  30528. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30529. }
  30530. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30531. return this;
  30532. };
  30533. SubMesh.prototype._checkCollision = function (collider) {
  30534. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30535. return boundingInfo._checkCollision(collider);
  30536. };
  30537. /**
  30538. * Updates the submesh BoundingInfo.
  30539. * Returns the Submesh.
  30540. */
  30541. SubMesh.prototype.updateBoundingInfo = function (world) {
  30542. var boundingInfo = this.getBoundingInfo();
  30543. if (!boundingInfo) {
  30544. this.refreshBoundingInfo();
  30545. boundingInfo = this.getBoundingInfo();
  30546. }
  30547. boundingInfo.update(world);
  30548. return this;
  30549. };
  30550. /**
  30551. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30552. * Boolean returned.
  30553. */
  30554. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30555. var boundingInfo = this.getBoundingInfo();
  30556. if (!boundingInfo) {
  30557. return false;
  30558. }
  30559. return boundingInfo.isInFrustum(frustumPlanes);
  30560. };
  30561. /**
  30562. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30563. * Boolean returned.
  30564. */
  30565. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30566. var boundingInfo = this.getBoundingInfo();
  30567. if (!boundingInfo) {
  30568. return false;
  30569. }
  30570. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30571. };
  30572. /**
  30573. * Renders the submesh.
  30574. * Returns it.
  30575. */
  30576. SubMesh.prototype.render = function (enableAlphaMode) {
  30577. this._renderingMesh.render(this, enableAlphaMode);
  30578. return this;
  30579. };
  30580. /**
  30581. * Returns a new Index Buffer.
  30582. * Type returned : WebGLBuffer.
  30583. */
  30584. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30585. if (!this._linesIndexBuffer) {
  30586. var linesIndices = [];
  30587. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30588. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30589. }
  30590. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30591. this.linesIndexCount = linesIndices.length;
  30592. }
  30593. return this._linesIndexBuffer;
  30594. };
  30595. /**
  30596. * True is the passed Ray intersects the submesh bounding box.
  30597. * Boolean returned.
  30598. */
  30599. SubMesh.prototype.canIntersects = function (ray) {
  30600. var boundingInfo = this.getBoundingInfo();
  30601. if (!boundingInfo) {
  30602. return false;
  30603. }
  30604. return ray.intersectsBox(boundingInfo.boundingBox);
  30605. };
  30606. /**
  30607. * Returns an object IntersectionInfo.
  30608. */
  30609. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30610. var intersectInfo = null;
  30611. // LineMesh first as it's also a Mesh...
  30612. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30613. var lineMesh = this._mesh;
  30614. // Line test
  30615. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30616. var p0 = positions[indices[index]];
  30617. var p1 = positions[indices[index + 1]];
  30618. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30619. if (length < 0) {
  30620. continue;
  30621. }
  30622. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30623. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30624. if (fastCheck) {
  30625. break;
  30626. }
  30627. }
  30628. }
  30629. }
  30630. else {
  30631. // Triangles test
  30632. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30633. var p0 = positions[indices[index]];
  30634. var p1 = positions[indices[index + 1]];
  30635. var p2 = positions[indices[index + 2]];
  30636. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30637. if (currentIntersectInfo) {
  30638. if (currentIntersectInfo.distance < 0) {
  30639. continue;
  30640. }
  30641. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30642. intersectInfo = currentIntersectInfo;
  30643. intersectInfo.faceId = index / 3;
  30644. if (fastCheck) {
  30645. break;
  30646. }
  30647. }
  30648. }
  30649. }
  30650. }
  30651. return intersectInfo;
  30652. };
  30653. SubMesh.prototype._rebuild = function () {
  30654. if (this._linesIndexBuffer) {
  30655. this._linesIndexBuffer = null;
  30656. }
  30657. };
  30658. // Clone
  30659. /**
  30660. * Creates a new Submesh from the passed Mesh.
  30661. */
  30662. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30663. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30664. if (!this.IsGlobal) {
  30665. var boundingInfo = this.getBoundingInfo();
  30666. if (!boundingInfo) {
  30667. return result;
  30668. }
  30669. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30670. }
  30671. return result;
  30672. };
  30673. // Dispose
  30674. /**
  30675. * Disposes the Submesh.
  30676. * Returns nothing.
  30677. */
  30678. SubMesh.prototype.dispose = function () {
  30679. if (this._linesIndexBuffer) {
  30680. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30681. this._linesIndexBuffer = null;
  30682. }
  30683. // Remove from mesh
  30684. var index = this._mesh.subMeshes.indexOf(this);
  30685. this._mesh.subMeshes.splice(index, 1);
  30686. };
  30687. // Statics
  30688. /**
  30689. * Creates a new Submesh from the passed parameters :
  30690. * - materialIndex (integer) : the index of the main mesh material.
  30691. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30692. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30693. * - mesh (Mesh) : the main mesh to create the submesh from.
  30694. * - renderingMesh (optional Mesh) : rendering mesh.
  30695. */
  30696. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30697. var minVertexIndex = Number.MAX_VALUE;
  30698. var maxVertexIndex = -Number.MAX_VALUE;
  30699. renderingMesh = (renderingMesh || mesh);
  30700. var indices = renderingMesh.getIndices();
  30701. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30702. var vertexIndex = indices[index];
  30703. if (vertexIndex < minVertexIndex)
  30704. minVertexIndex = vertexIndex;
  30705. if (vertexIndex > maxVertexIndex)
  30706. maxVertexIndex = vertexIndex;
  30707. }
  30708. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30709. };
  30710. return SubMesh;
  30711. }(BaseSubMesh));
  30712. BABYLON.SubMesh = SubMesh;
  30713. })(BABYLON || (BABYLON = {}));
  30714. //# sourceMappingURL=babylon.subMesh.js.map
  30715. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30716. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30717. s = arguments[i];
  30718. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30719. t[p] = s[p];
  30720. }
  30721. return t;
  30722. };
  30723. var BABYLON;
  30724. (function (BABYLON) {
  30725. /**
  30726. * Manages the defines for the Material.
  30727. */
  30728. var MaterialDefines = /** @class */ (function () {
  30729. function MaterialDefines() {
  30730. this._isDirty = true;
  30731. this._areLightsDirty = true;
  30732. this._areAttributesDirty = true;
  30733. this._areTexturesDirty = true;
  30734. this._areFresnelDirty = true;
  30735. this._areMiscDirty = true;
  30736. this._areImageProcessingDirty = true;
  30737. this._normals = false;
  30738. this._uvs = false;
  30739. this._needNormals = false;
  30740. this._needUVs = false;
  30741. }
  30742. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30743. /**
  30744. * Specifies if the material needs to be re-calculated.
  30745. */
  30746. get: function () {
  30747. return this._isDirty;
  30748. },
  30749. enumerable: true,
  30750. configurable: true
  30751. });
  30752. /**
  30753. * Marks the material to indicate that it has been re-calculated.
  30754. */
  30755. MaterialDefines.prototype.markAsProcessed = function () {
  30756. this._isDirty = false;
  30757. this._areAttributesDirty = false;
  30758. this._areTexturesDirty = false;
  30759. this._areFresnelDirty = false;
  30760. this._areLightsDirty = false;
  30761. this._areMiscDirty = false;
  30762. this._areImageProcessingDirty = false;
  30763. };
  30764. /**
  30765. * Marks the material to indicate that it needs to be re-calculated.
  30766. */
  30767. MaterialDefines.prototype.markAsUnprocessed = function () {
  30768. this._isDirty = true;
  30769. };
  30770. /**
  30771. * Marks the material to indicate all of its defines need to be re-calculated.
  30772. */
  30773. MaterialDefines.prototype.markAllAsDirty = function () {
  30774. this._areTexturesDirty = true;
  30775. this._areAttributesDirty = true;
  30776. this._areLightsDirty = true;
  30777. this._areFresnelDirty = true;
  30778. this._areMiscDirty = true;
  30779. this._areImageProcessingDirty = true;
  30780. this._isDirty = true;
  30781. };
  30782. /**
  30783. * Marks the material to indicate that image processing needs to be re-calculated.
  30784. */
  30785. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30786. this._areImageProcessingDirty = true;
  30787. this._isDirty = true;
  30788. };
  30789. /**
  30790. * Marks the material to indicate the lights need to be re-calculated.
  30791. */
  30792. MaterialDefines.prototype.markAsLightDirty = function () {
  30793. this._areLightsDirty = true;
  30794. this._isDirty = true;
  30795. };
  30796. /**
  30797. * Marks the attribute state as changed.
  30798. */
  30799. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30800. this._areAttributesDirty = true;
  30801. this._isDirty = true;
  30802. };
  30803. /**
  30804. * Marks the texture state as changed.
  30805. */
  30806. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30807. this._areTexturesDirty = true;
  30808. this._isDirty = true;
  30809. };
  30810. /**
  30811. * Marks the fresnel state as changed.
  30812. */
  30813. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30814. this._areFresnelDirty = true;
  30815. this._isDirty = true;
  30816. };
  30817. /**
  30818. * Marks the misc state as changed.
  30819. */
  30820. MaterialDefines.prototype.markAsMiscDirty = function () {
  30821. this._areMiscDirty = true;
  30822. this._isDirty = true;
  30823. };
  30824. /**
  30825. * Rebuilds the material defines.
  30826. */
  30827. MaterialDefines.prototype.rebuild = function () {
  30828. if (this._keys) {
  30829. delete this._keys;
  30830. }
  30831. this._keys = [];
  30832. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30833. var key = _a[_i];
  30834. if (key[0] === "_") {
  30835. continue;
  30836. }
  30837. this._keys.push(key);
  30838. }
  30839. };
  30840. /**
  30841. * Specifies if two material defines are equal.
  30842. * @param other - A material define instance to compare to.
  30843. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30844. */
  30845. MaterialDefines.prototype.isEqual = function (other) {
  30846. if (this._keys.length !== other._keys.length) {
  30847. return false;
  30848. }
  30849. for (var index = 0; index < this._keys.length; index++) {
  30850. var prop = this._keys[index];
  30851. if (this[prop] !== other[prop]) {
  30852. return false;
  30853. }
  30854. }
  30855. return true;
  30856. };
  30857. /**
  30858. * Clones this instance's defines to another instance.
  30859. * @param other - material defines to clone values to.
  30860. */
  30861. MaterialDefines.prototype.cloneTo = function (other) {
  30862. if (this._keys.length !== other._keys.length) {
  30863. other._keys = this._keys.slice(0);
  30864. }
  30865. for (var index = 0; index < this._keys.length; index++) {
  30866. var prop = this._keys[index];
  30867. other[prop] = this[prop];
  30868. }
  30869. };
  30870. /**
  30871. * Resets the material define values.
  30872. */
  30873. MaterialDefines.prototype.reset = function () {
  30874. for (var index = 0; index < this._keys.length; index++) {
  30875. var prop = this._keys[index];
  30876. if (typeof (this[prop]) === "number") {
  30877. this[prop] = 0;
  30878. }
  30879. else {
  30880. this[prop] = false;
  30881. }
  30882. }
  30883. };
  30884. /**
  30885. * Converts the material define values to a string.
  30886. * @returns - String of material define information.
  30887. */
  30888. MaterialDefines.prototype.toString = function () {
  30889. var result = "";
  30890. for (var index = 0; index < this._keys.length; index++) {
  30891. var prop = this._keys[index];
  30892. var value = this[prop];
  30893. if (typeof (value) === "number") {
  30894. result += "#define " + prop + " " + this[prop] + "\n";
  30895. }
  30896. else if (value) {
  30897. result += "#define " + prop + "\n";
  30898. }
  30899. }
  30900. return result;
  30901. };
  30902. return MaterialDefines;
  30903. }());
  30904. BABYLON.MaterialDefines = MaterialDefines;
  30905. /**
  30906. * This offers the main features of a material in BJS.
  30907. */
  30908. var Material = /** @class */ (function () {
  30909. /**
  30910. * Creates a material instance.
  30911. * @param name - The name of the material.
  30912. * @param scene - The BJS scene to reference.
  30913. * @param doNotAdd - Specifies if the material should be added to the scene.
  30914. */
  30915. function Material(name, scene, doNotAdd) {
  30916. /**
  30917. * Specifies if the ready state should be checked on each call.
  30918. */
  30919. this.checkReadyOnEveryCall = false;
  30920. /**
  30921. * Specifies if the ready state should be checked once.
  30922. */
  30923. this.checkReadyOnlyOnce = false;
  30924. /**
  30925. * The state of the material.
  30926. */
  30927. this.state = "";
  30928. /**
  30929. * The alpha value of the material.
  30930. */
  30931. this._alpha = 1.0;
  30932. /**
  30933. * Specifies if back face culling is enabled.
  30934. */
  30935. this._backFaceCulling = true;
  30936. /**
  30937. * Specifies if the material should be serialized.
  30938. */
  30939. this.doNotSerialize = false;
  30940. /**
  30941. * Specifies if the effect should be stored on sub meshes.
  30942. */
  30943. this.storeEffectOnSubMeshes = false;
  30944. /**
  30945. * An event triggered when the material is disposed.
  30946. * @type {BABYLON.Observable}
  30947. */
  30948. this.onDisposeObservable = new BABYLON.Observable();
  30949. /**
  30950. * An event triggered when the material is bound.
  30951. * @type {BABYLON.Observable}
  30952. */
  30953. this.onBindObservable = new BABYLON.Observable();
  30954. /**
  30955. * An event triggered when the material is unbound.
  30956. * @type {BABYLON.Observable}
  30957. */
  30958. this.onUnBindObservable = new BABYLON.Observable();
  30959. /**
  30960. * Stores the value of the alpha mode.
  30961. */
  30962. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30963. /**
  30964. * Stores the state of the need depth pre-pass value.
  30965. */
  30966. this._needDepthPrePass = false;
  30967. /**
  30968. * Specifies if depth writing should be disabled.
  30969. */
  30970. this.disableDepthWrite = false;
  30971. /**
  30972. * Specifies if depth writing should be forced.
  30973. */
  30974. this.forceDepthWrite = false;
  30975. /**
  30976. * Specifies if there should be a separate pass for culling.
  30977. */
  30978. this.separateCullingPass = false;
  30979. /**
  30980. * Stores the state specifing if fog should be enabled.
  30981. */
  30982. this._fogEnabled = true;
  30983. /**
  30984. * Stores the size of points.
  30985. */
  30986. this.pointSize = 1.0;
  30987. /**
  30988. * Stores the z offset value.
  30989. */
  30990. this.zOffset = 0;
  30991. /**
  30992. * Specifies if the material was previously ready.
  30993. */
  30994. this._wasPreviouslyReady = false;
  30995. /**
  30996. * Stores the fill mode state.
  30997. */
  30998. this._fillMode = Material.TriangleFillMode;
  30999. this.name = name;
  31000. this.id = name || BABYLON.Tools.RandomId();
  31001. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31002. if (this._scene.useRightHandedSystem) {
  31003. this.sideOrientation = Material.ClockWiseSideOrientation;
  31004. }
  31005. else {
  31006. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31007. }
  31008. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31009. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31010. if (!doNotAdd) {
  31011. this._scene.materials.push(this);
  31012. }
  31013. }
  31014. Object.defineProperty(Material, "TriangleFillMode", {
  31015. /**
  31016. * Returns the triangle fill mode.
  31017. */
  31018. get: function () {
  31019. return Material._TriangleFillMode;
  31020. },
  31021. enumerable: true,
  31022. configurable: true
  31023. });
  31024. Object.defineProperty(Material, "WireFrameFillMode", {
  31025. /**
  31026. * Returns the wireframe mode.
  31027. */
  31028. get: function () {
  31029. return Material._WireFrameFillMode;
  31030. },
  31031. enumerable: true,
  31032. configurable: true
  31033. });
  31034. Object.defineProperty(Material, "PointFillMode", {
  31035. /**
  31036. * Returns the point fill mode.
  31037. */
  31038. get: function () {
  31039. return Material._PointFillMode;
  31040. },
  31041. enumerable: true,
  31042. configurable: true
  31043. });
  31044. Object.defineProperty(Material, "PointListDrawMode", {
  31045. /**
  31046. * Returns the point list draw mode.
  31047. */
  31048. get: function () {
  31049. return Material._PointListDrawMode;
  31050. },
  31051. enumerable: true,
  31052. configurable: true
  31053. });
  31054. Object.defineProperty(Material, "LineListDrawMode", {
  31055. /**
  31056. * Returns the line list draw mode.
  31057. */
  31058. get: function () {
  31059. return Material._LineListDrawMode;
  31060. },
  31061. enumerable: true,
  31062. configurable: true
  31063. });
  31064. Object.defineProperty(Material, "LineLoopDrawMode", {
  31065. /**
  31066. * Returns the line loop draw mode.
  31067. */
  31068. get: function () {
  31069. return Material._LineLoopDrawMode;
  31070. },
  31071. enumerable: true,
  31072. configurable: true
  31073. });
  31074. Object.defineProperty(Material, "LineStripDrawMode", {
  31075. /**
  31076. * Returns the line strip draw mode.
  31077. */
  31078. get: function () {
  31079. return Material._LineStripDrawMode;
  31080. },
  31081. enumerable: true,
  31082. configurable: true
  31083. });
  31084. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31085. /**
  31086. * Returns the triangle strip draw mode.
  31087. */
  31088. get: function () {
  31089. return Material._TriangleStripDrawMode;
  31090. },
  31091. enumerable: true,
  31092. configurable: true
  31093. });
  31094. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31095. /**
  31096. * Returns the triangle fan draw mode.
  31097. */
  31098. get: function () {
  31099. return Material._TriangleFanDrawMode;
  31100. },
  31101. enumerable: true,
  31102. configurable: true
  31103. });
  31104. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31105. /**
  31106. * Returns the clock-wise side orientation.
  31107. */
  31108. get: function () {
  31109. return Material._ClockWiseSideOrientation;
  31110. },
  31111. enumerable: true,
  31112. configurable: true
  31113. });
  31114. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31115. /**
  31116. * Returns the counter clock-wise side orientation.
  31117. */
  31118. get: function () {
  31119. return Material._CounterClockWiseSideOrientation;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Object.defineProperty(Material, "TextureDirtyFlag", {
  31125. /**
  31126. * Returns the dirty texture flag value.
  31127. */
  31128. get: function () {
  31129. return Material._TextureDirtyFlag;
  31130. },
  31131. enumerable: true,
  31132. configurable: true
  31133. });
  31134. Object.defineProperty(Material, "LightDirtyFlag", {
  31135. /**
  31136. * Returns the dirty light flag value.
  31137. */
  31138. get: function () {
  31139. return Material._LightDirtyFlag;
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31145. /**
  31146. * Returns the dirty fresnel flag value.
  31147. */
  31148. get: function () {
  31149. return Material._FresnelDirtyFlag;
  31150. },
  31151. enumerable: true,
  31152. configurable: true
  31153. });
  31154. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31155. /**
  31156. * Returns the dirty attributes flag value.
  31157. */
  31158. get: function () {
  31159. return Material._AttributesDirtyFlag;
  31160. },
  31161. enumerable: true,
  31162. configurable: true
  31163. });
  31164. Object.defineProperty(Material, "MiscDirtyFlag", {
  31165. /**
  31166. * Returns the dirty misc flag value.
  31167. */
  31168. get: function () {
  31169. return Material._MiscDirtyFlag;
  31170. },
  31171. enumerable: true,
  31172. configurable: true
  31173. });
  31174. Object.defineProperty(Material.prototype, "alpha", {
  31175. /**
  31176. * Gets the alpha value of the material.
  31177. */
  31178. get: function () {
  31179. return this._alpha;
  31180. },
  31181. /**
  31182. * Sets the alpha value of the material.
  31183. */
  31184. set: function (value) {
  31185. if (this._alpha === value) {
  31186. return;
  31187. }
  31188. this._alpha = value;
  31189. this.markAsDirty(Material.MiscDirtyFlag);
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31195. /**
  31196. * Gets the back-face culling state.
  31197. */
  31198. get: function () {
  31199. return this._backFaceCulling;
  31200. },
  31201. /**
  31202. * Sets the back-face culling state.
  31203. */
  31204. set: function (value) {
  31205. if (this._backFaceCulling === value) {
  31206. return;
  31207. }
  31208. this._backFaceCulling = value;
  31209. this.markAsDirty(Material.TextureDirtyFlag);
  31210. },
  31211. enumerable: true,
  31212. configurable: true
  31213. });
  31214. Object.defineProperty(Material.prototype, "onDispose", {
  31215. /**
  31216. * Called during a dispose event.
  31217. */
  31218. set: function (callback) {
  31219. if (this._onDisposeObserver) {
  31220. this.onDisposeObservable.remove(this._onDisposeObserver);
  31221. }
  31222. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31223. },
  31224. enumerable: true,
  31225. configurable: true
  31226. });
  31227. Object.defineProperty(Material.prototype, "onBind", {
  31228. /**
  31229. * Called during a bind event.
  31230. */
  31231. set: function (callback) {
  31232. if (this._onBindObserver) {
  31233. this.onBindObservable.remove(this._onBindObserver);
  31234. }
  31235. this._onBindObserver = this.onBindObservable.add(callback);
  31236. },
  31237. enumerable: true,
  31238. configurable: true
  31239. });
  31240. Object.defineProperty(Material.prototype, "alphaMode", {
  31241. /**
  31242. * Gets the value of the alpha mode.
  31243. */
  31244. get: function () {
  31245. return this._alphaMode;
  31246. },
  31247. /**
  31248. * Sets the value of the alpha mode.
  31249. */
  31250. set: function (value) {
  31251. if (this._alphaMode === value) {
  31252. return;
  31253. }
  31254. this._alphaMode = value;
  31255. this.markAsDirty(Material.TextureDirtyFlag);
  31256. },
  31257. enumerable: true,
  31258. configurable: true
  31259. });
  31260. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31261. /**
  31262. * Gets the depth pre-pass value.
  31263. */
  31264. get: function () {
  31265. return this._needDepthPrePass;
  31266. },
  31267. /**
  31268. * Sets the need depth pre-pass value.
  31269. */
  31270. set: function (value) {
  31271. if (this._needDepthPrePass === value) {
  31272. return;
  31273. }
  31274. this._needDepthPrePass = value;
  31275. if (this._needDepthPrePass) {
  31276. this.checkReadyOnEveryCall = true;
  31277. }
  31278. },
  31279. enumerable: true,
  31280. configurable: true
  31281. });
  31282. Object.defineProperty(Material.prototype, "fogEnabled", {
  31283. /**
  31284. * Gets the value of the fog enabled state.
  31285. */
  31286. get: function () {
  31287. return this._fogEnabled;
  31288. },
  31289. /**
  31290. * Sets the state for enabling fog.
  31291. */
  31292. set: function (value) {
  31293. if (this._fogEnabled === value) {
  31294. return;
  31295. }
  31296. this._fogEnabled = value;
  31297. this.markAsDirty(Material.MiscDirtyFlag);
  31298. },
  31299. enumerable: true,
  31300. configurable: true
  31301. });
  31302. Object.defineProperty(Material.prototype, "wireframe", {
  31303. /**
  31304. * Gets a value specifying if wireframe mode is enabled.
  31305. */
  31306. get: function () {
  31307. return this._fillMode === Material.WireFrameFillMode;
  31308. },
  31309. /**
  31310. * Sets the state of wireframe mode.
  31311. */
  31312. set: function (value) {
  31313. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31314. },
  31315. enumerable: true,
  31316. configurable: true
  31317. });
  31318. Object.defineProperty(Material.prototype, "pointsCloud", {
  31319. /**
  31320. * Gets the value specifying if point clouds are enabled.
  31321. */
  31322. get: function () {
  31323. return this._fillMode === Material.PointFillMode;
  31324. },
  31325. /**
  31326. * Sets the state of point cloud mode.
  31327. */
  31328. set: function (value) {
  31329. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31330. },
  31331. enumerable: true,
  31332. configurable: true
  31333. });
  31334. Object.defineProperty(Material.prototype, "fillMode", {
  31335. /**
  31336. * Gets the material fill mode.
  31337. */
  31338. get: function () {
  31339. return this._fillMode;
  31340. },
  31341. /**
  31342. * Sets the material fill mode.
  31343. */
  31344. set: function (value) {
  31345. if (this._fillMode === value) {
  31346. return;
  31347. }
  31348. this._fillMode = value;
  31349. this.markAsDirty(Material.MiscDirtyFlag);
  31350. },
  31351. enumerable: true,
  31352. configurable: true
  31353. });
  31354. /**
  31355. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31356. * subclasses should override adding information pertainent to themselves.
  31357. * @returns - String with material information.
  31358. */
  31359. Material.prototype.toString = function (fullDetails) {
  31360. var ret = "Name: " + this.name;
  31361. if (fullDetails) {
  31362. }
  31363. return ret;
  31364. };
  31365. /**
  31366. * Gets the class name of the material.
  31367. * @returns - String with the class name of the material.
  31368. */
  31369. Material.prototype.getClassName = function () {
  31370. return "Material";
  31371. };
  31372. Object.defineProperty(Material.prototype, "isFrozen", {
  31373. /**
  31374. * Specifies if updates for the material been locked.
  31375. */
  31376. get: function () {
  31377. return this.checkReadyOnlyOnce;
  31378. },
  31379. enumerable: true,
  31380. configurable: true
  31381. });
  31382. /**
  31383. * Locks updates for the material.
  31384. */
  31385. Material.prototype.freeze = function () {
  31386. this.checkReadyOnlyOnce = true;
  31387. };
  31388. /**
  31389. * Unlocks updates for the material.
  31390. */
  31391. Material.prototype.unfreeze = function () {
  31392. this.checkReadyOnlyOnce = false;
  31393. };
  31394. /**
  31395. * Specifies if the material is ready to be used.
  31396. * @param mesh - BJS mesh.
  31397. * @param useInstances - Specifies if instances should be used.
  31398. * @returns - Boolean indicating if the material is ready to be used.
  31399. */
  31400. Material.prototype.isReady = function (mesh, useInstances) {
  31401. return true;
  31402. };
  31403. /**
  31404. * Specifies that the submesh is ready to be used.
  31405. * @param mesh - BJS mesh.
  31406. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31407. * @param useInstances - Specifies that instances should be used.
  31408. * @returns - boolean indicating that the submesh is ready or not.
  31409. */
  31410. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31411. return false;
  31412. };
  31413. /**
  31414. * Returns the material effect.
  31415. * @returns - Nullable material effect.
  31416. */
  31417. Material.prototype.getEffect = function () {
  31418. return this._effect;
  31419. };
  31420. /**
  31421. * Returns the BJS scene.
  31422. * @returns - BJS Scene.
  31423. */
  31424. Material.prototype.getScene = function () {
  31425. return this._scene;
  31426. };
  31427. /**
  31428. * Specifies if the material will require alpha blending
  31429. * @returns - Boolean specifying if alpha blending is needed.
  31430. */
  31431. Material.prototype.needAlphaBlending = function () {
  31432. return (this.alpha < 1.0);
  31433. };
  31434. /**
  31435. * Specifies if the mesh will require alpha blending.
  31436. * @param mesh - BJS mesh.
  31437. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31438. */
  31439. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31440. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31441. };
  31442. /**
  31443. * Specifies if this material should be rendered in alpha test mode.
  31444. * @returns - Boolean specifying if an alpha test is needed.
  31445. */
  31446. Material.prototype.needAlphaTesting = function () {
  31447. return false;
  31448. };
  31449. /**
  31450. * Gets the texture used for the alpha test.
  31451. * @returns - Nullable alpha test texture.
  31452. */
  31453. Material.prototype.getAlphaTestTexture = function () {
  31454. return null;
  31455. };
  31456. /**
  31457. * Marks the material to indicate that it needs to be re-calculated.
  31458. */
  31459. Material.prototype.markDirty = function () {
  31460. this._wasPreviouslyReady = false;
  31461. };
  31462. Material.prototype._preBind = function (effect, overrideOrientation) {
  31463. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31464. var engine = this._scene.getEngine();
  31465. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31466. var reverse = orientation === Material.ClockWiseSideOrientation;
  31467. engine.enableEffect(effect ? effect : this._effect);
  31468. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31469. return reverse;
  31470. };
  31471. /**
  31472. * Binds the material to the mesh.
  31473. * @param world - World transformation matrix.
  31474. * @param mesh - Mesh to bind the material to.
  31475. */
  31476. Material.prototype.bind = function (world, mesh) {
  31477. };
  31478. /**
  31479. * Binds the submesh to the material.
  31480. * @param world - World transformation matrix.
  31481. * @param mesh - Mesh containing the submesh.
  31482. * @param subMesh - Submesh to bind the material to.
  31483. */
  31484. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31485. };
  31486. /**
  31487. * Binds the world matrix to the material.
  31488. * @param world - World transformation matrix.
  31489. */
  31490. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31491. };
  31492. /**
  31493. * Binds the scene's uniform buffer to the effect.
  31494. * @param effect - Effect to bind to the scene uniform buffer.
  31495. * @param sceneUbo - Scene uniform buffer.
  31496. */
  31497. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31498. sceneUbo.bindToEffect(effect, "Scene");
  31499. };
  31500. /**
  31501. * Binds the view matrix to the effect.
  31502. * @param effect - Effect to bind the view matrix to.
  31503. */
  31504. Material.prototype.bindView = function (effect) {
  31505. if (!this._useUBO) {
  31506. effect.setMatrix("view", this.getScene().getViewMatrix());
  31507. }
  31508. else {
  31509. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31510. }
  31511. };
  31512. /**
  31513. * Binds the view projection matrix to the effect.
  31514. * @param effect - Effect to bind the view projection matrix to.
  31515. */
  31516. Material.prototype.bindViewProjection = function (effect) {
  31517. if (!this._useUBO) {
  31518. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31519. }
  31520. else {
  31521. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31522. }
  31523. };
  31524. /**
  31525. * Specifies if material alpha testing should be turned on for the mesh.
  31526. * @param mesh - BJS mesh.
  31527. */
  31528. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31529. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31530. };
  31531. /**
  31532. * Processes to execute after binding the material to a mesh.
  31533. * @param mesh - BJS mesh.
  31534. */
  31535. Material.prototype._afterBind = function (mesh) {
  31536. this._scene._cachedMaterial = this;
  31537. if (mesh) {
  31538. this._scene._cachedVisibility = mesh.visibility;
  31539. }
  31540. else {
  31541. this._scene._cachedVisibility = 1;
  31542. }
  31543. if (mesh) {
  31544. this.onBindObservable.notifyObservers(mesh);
  31545. }
  31546. if (this.disableDepthWrite) {
  31547. var engine = this._scene.getEngine();
  31548. this._cachedDepthWriteState = engine.getDepthWrite();
  31549. engine.setDepthWrite(false);
  31550. }
  31551. };
  31552. /**
  31553. * Unbinds the material from the mesh.
  31554. */
  31555. Material.prototype.unbind = function () {
  31556. this.onUnBindObservable.notifyObservers(this);
  31557. if (this.disableDepthWrite) {
  31558. var engine = this._scene.getEngine();
  31559. engine.setDepthWrite(this._cachedDepthWriteState);
  31560. }
  31561. };
  31562. /**
  31563. * Gets the active textures from the material.
  31564. * @returns - Array of textures.
  31565. */
  31566. Material.prototype.getActiveTextures = function () {
  31567. return [];
  31568. };
  31569. /**
  31570. * Specifies if the material uses a texture.
  31571. * @param texture - Texture to check against the material.
  31572. * @returns - Boolean specifying if the material uses the texture.
  31573. */
  31574. Material.prototype.hasTexture = function (texture) {
  31575. return false;
  31576. };
  31577. /**
  31578. * Makes a duplicate of the material, and gives it a new name.
  31579. * @param name - Name to call the duplicated material.
  31580. * @returns - Nullable cloned material
  31581. */
  31582. Material.prototype.clone = function (name) {
  31583. return null;
  31584. };
  31585. /**
  31586. * Gets the meshes bound to the material.
  31587. * @returns - Array of meshes bound to the material.
  31588. */
  31589. Material.prototype.getBindedMeshes = function () {
  31590. var result = new Array();
  31591. for (var index = 0; index < this._scene.meshes.length; index++) {
  31592. var mesh = this._scene.meshes[index];
  31593. if (mesh.material === this) {
  31594. result.push(mesh);
  31595. }
  31596. }
  31597. return result;
  31598. };
  31599. /**
  31600. * Force shader compilation
  31601. * @param mesh - BJS mesh.
  31602. * @param onCompiled - function to execute once the material is compiled.
  31603. * @param options - options to pass to this function.
  31604. */
  31605. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31606. var _this = this;
  31607. var localOptions = __assign({ clipPlane: false }, options);
  31608. var subMesh = new BABYLON.BaseSubMesh();
  31609. var scene = this.getScene();
  31610. var checkReady = function () {
  31611. if (!_this._scene || !_this._scene.getEngine()) {
  31612. return;
  31613. }
  31614. if (subMesh._materialDefines) {
  31615. subMesh._materialDefines._renderId = -1;
  31616. }
  31617. var clipPlaneState = scene.clipPlane;
  31618. if (localOptions.clipPlane) {
  31619. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31620. }
  31621. if (_this.storeEffectOnSubMeshes) {
  31622. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31623. if (onCompiled) {
  31624. onCompiled(_this);
  31625. }
  31626. }
  31627. else {
  31628. setTimeout(checkReady, 16);
  31629. }
  31630. }
  31631. else {
  31632. if (_this.isReady(mesh)) {
  31633. if (onCompiled) {
  31634. onCompiled(_this);
  31635. }
  31636. }
  31637. else {
  31638. setTimeout(checkReady, 16);
  31639. }
  31640. }
  31641. if (localOptions.clipPlane) {
  31642. scene.clipPlane = clipPlaneState;
  31643. }
  31644. };
  31645. checkReady();
  31646. };
  31647. /**
  31648. * Force shader compilation.
  31649. * @param mesh The mesh that will use this material
  31650. * @param options Additional options for compiling the shaders
  31651. * @returns A promise that resolves when the compilation completes
  31652. */
  31653. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31654. var _this = this;
  31655. return new Promise(function (resolve) {
  31656. _this.forceCompilation(mesh, function () {
  31657. resolve();
  31658. }, options);
  31659. });
  31660. };
  31661. /**
  31662. * Marks a define in the material to indicate that it needs to be re-computed.
  31663. * @param flag - Material define flag.
  31664. */
  31665. Material.prototype.markAsDirty = function (flag) {
  31666. if (flag & Material.TextureDirtyFlag) {
  31667. this._markAllSubMeshesAsTexturesDirty();
  31668. }
  31669. if (flag & Material.LightDirtyFlag) {
  31670. this._markAllSubMeshesAsLightsDirty();
  31671. }
  31672. if (flag & Material.FresnelDirtyFlag) {
  31673. this._markAllSubMeshesAsFresnelDirty();
  31674. }
  31675. if (flag & Material.AttributesDirtyFlag) {
  31676. this._markAllSubMeshesAsAttributesDirty();
  31677. }
  31678. if (flag & Material.MiscDirtyFlag) {
  31679. this._markAllSubMeshesAsMiscDirty();
  31680. }
  31681. this.getScene().resetCachedMaterial();
  31682. };
  31683. /**
  31684. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31685. * @param func - function which checks material defines against the submeshes.
  31686. */
  31687. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31688. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31689. var mesh = _a[_i];
  31690. if (!mesh.subMeshes) {
  31691. continue;
  31692. }
  31693. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31694. var subMesh = _c[_b];
  31695. if (subMesh.getMaterial() !== this) {
  31696. continue;
  31697. }
  31698. if (!subMesh._materialDefines) {
  31699. continue;
  31700. }
  31701. func(subMesh._materialDefines);
  31702. }
  31703. }
  31704. };
  31705. /**
  31706. * Indicates that image processing needs to be re-calculated for all submeshes.
  31707. */
  31708. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31709. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31710. };
  31711. /**
  31712. * Indicates that textures need to be re-calculated for all submeshes.
  31713. */
  31714. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31715. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31716. };
  31717. /**
  31718. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31719. */
  31720. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31721. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31722. };
  31723. /**
  31724. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31725. */
  31726. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31727. this._markAllSubMeshesAsDirty(function (defines) {
  31728. defines.markAsFresnelDirty();
  31729. defines.markAsMiscDirty();
  31730. });
  31731. };
  31732. /**
  31733. * Indicates that lights need to be re-calculated for all submeshes.
  31734. */
  31735. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31736. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31737. };
  31738. /**
  31739. * Indicates that attributes need to be re-calculated for all submeshes.
  31740. */
  31741. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31742. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31743. };
  31744. /**
  31745. * Indicates that misc needs to be re-calculated for all submeshes.
  31746. */
  31747. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31748. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31749. };
  31750. /**
  31751. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31752. */
  31753. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31754. this._markAllSubMeshesAsDirty(function (defines) {
  31755. defines.markAsTexturesDirty();
  31756. defines.markAsMiscDirty();
  31757. });
  31758. };
  31759. /**
  31760. * Disposes the material.
  31761. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31762. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31763. */
  31764. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31765. // Animations
  31766. this.getScene().stopAnimation(this);
  31767. this.getScene().freeProcessedMaterials();
  31768. // Remove from scene
  31769. var index = this._scene.materials.indexOf(this);
  31770. if (index >= 0) {
  31771. this._scene.materials.splice(index, 1);
  31772. }
  31773. // Remove from meshes
  31774. for (index = 0; index < this._scene.meshes.length; index++) {
  31775. var mesh = this._scene.meshes[index];
  31776. if (mesh.material === this) {
  31777. mesh.material = null;
  31778. if (mesh.geometry) {
  31779. var geometry = (mesh.geometry);
  31780. if (this.storeEffectOnSubMeshes) {
  31781. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31782. var subMesh = _a[_i];
  31783. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31784. if (forceDisposeEffect && subMesh._materialEffect) {
  31785. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31786. }
  31787. }
  31788. }
  31789. else {
  31790. geometry._releaseVertexArrayObject(this._effect);
  31791. }
  31792. }
  31793. }
  31794. }
  31795. this._uniformBuffer.dispose();
  31796. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31797. if (forceDisposeEffect && this._effect) {
  31798. if (!this.storeEffectOnSubMeshes) {
  31799. this._scene.getEngine()._releaseEffect(this._effect);
  31800. }
  31801. this._effect = null;
  31802. }
  31803. // Callback
  31804. this.onDisposeObservable.notifyObservers(this);
  31805. this.onDisposeObservable.clear();
  31806. this.onBindObservable.clear();
  31807. this.onUnBindObservable.clear();
  31808. };
  31809. /**
  31810. * Serializes this material.
  31811. * @returns - serialized material object.
  31812. */
  31813. Material.prototype.serialize = function () {
  31814. return BABYLON.SerializationHelper.Serialize(this);
  31815. };
  31816. /**
  31817. * Creates a MultiMaterial from parse MultiMaterial data.
  31818. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31819. * @param scene - BJS scene.
  31820. * @returns - MultiMaterial.
  31821. */
  31822. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31823. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31824. multiMaterial.id = parsedMultiMaterial.id;
  31825. if (BABYLON.Tags) {
  31826. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31827. }
  31828. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31829. var subMatId = parsedMultiMaterial.materials[matIndex];
  31830. if (subMatId) {
  31831. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31832. }
  31833. else {
  31834. multiMaterial.subMaterials.push(null);
  31835. }
  31836. }
  31837. return multiMaterial;
  31838. };
  31839. /**
  31840. * Creates a material from parsed material data.
  31841. * @param parsedMaterial - Parsed material data.
  31842. * @param scene - BJS scene.
  31843. * @param rootUrl - Root URL containing the material information.
  31844. * @returns - Parsed material.
  31845. */
  31846. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31847. if (!parsedMaterial.customType) {
  31848. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31849. }
  31850. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31851. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31852. if (!BABYLON.LegacyPBRMaterial) {
  31853. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31854. return;
  31855. }
  31856. }
  31857. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31858. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31859. ;
  31860. };
  31861. // Triangle views
  31862. Material._TriangleFillMode = 0;
  31863. Material._WireFrameFillMode = 1;
  31864. Material._PointFillMode = 2;
  31865. // Draw modes
  31866. Material._PointListDrawMode = 3;
  31867. Material._LineListDrawMode = 4;
  31868. Material._LineLoopDrawMode = 5;
  31869. Material._LineStripDrawMode = 6;
  31870. Material._TriangleStripDrawMode = 7;
  31871. Material._TriangleFanDrawMode = 8;
  31872. /**
  31873. * Stores the clock-wise side orientation.
  31874. */
  31875. Material._ClockWiseSideOrientation = 0;
  31876. /**
  31877. * Stores the counter clock-wise side orientation.
  31878. */
  31879. Material._CounterClockWiseSideOrientation = 1;
  31880. /**
  31881. * The dirty texture flag value.
  31882. */
  31883. Material._TextureDirtyFlag = 1;
  31884. /**
  31885. * The dirty light flag value.
  31886. */
  31887. Material._LightDirtyFlag = 2;
  31888. /**
  31889. * The dirty fresnel flag value.
  31890. */
  31891. Material._FresnelDirtyFlag = 4;
  31892. /**
  31893. * The dirty attribute flag value.
  31894. */
  31895. Material._AttributesDirtyFlag = 8;
  31896. /**
  31897. * The dirty misc flag value.
  31898. */
  31899. Material._MiscDirtyFlag = 16;
  31900. __decorate([
  31901. BABYLON.serialize()
  31902. ], Material.prototype, "id", void 0);
  31903. __decorate([
  31904. BABYLON.serialize()
  31905. ], Material.prototype, "name", void 0);
  31906. __decorate([
  31907. BABYLON.serialize()
  31908. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31909. __decorate([
  31910. BABYLON.serialize()
  31911. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31912. __decorate([
  31913. BABYLON.serialize()
  31914. ], Material.prototype, "state", void 0);
  31915. __decorate([
  31916. BABYLON.serialize("alpha")
  31917. ], Material.prototype, "_alpha", void 0);
  31918. __decorate([
  31919. BABYLON.serialize("backFaceCulling")
  31920. ], Material.prototype, "_backFaceCulling", void 0);
  31921. __decorate([
  31922. BABYLON.serialize()
  31923. ], Material.prototype, "sideOrientation", void 0);
  31924. __decorate([
  31925. BABYLON.serialize("alphaMode")
  31926. ], Material.prototype, "_alphaMode", void 0);
  31927. __decorate([
  31928. BABYLON.serialize()
  31929. ], Material.prototype, "_needDepthPrePass", void 0);
  31930. __decorate([
  31931. BABYLON.serialize()
  31932. ], Material.prototype, "disableDepthWrite", void 0);
  31933. __decorate([
  31934. BABYLON.serialize()
  31935. ], Material.prototype, "forceDepthWrite", void 0);
  31936. __decorate([
  31937. BABYLON.serialize()
  31938. ], Material.prototype, "separateCullingPass", void 0);
  31939. __decorate([
  31940. BABYLON.serialize("fogEnabled")
  31941. ], Material.prototype, "_fogEnabled", void 0);
  31942. __decorate([
  31943. BABYLON.serialize()
  31944. ], Material.prototype, "pointSize", void 0);
  31945. __decorate([
  31946. BABYLON.serialize()
  31947. ], Material.prototype, "zOffset", void 0);
  31948. __decorate([
  31949. BABYLON.serialize()
  31950. ], Material.prototype, "wireframe", null);
  31951. __decorate([
  31952. BABYLON.serialize()
  31953. ], Material.prototype, "pointsCloud", null);
  31954. __decorate([
  31955. BABYLON.serialize()
  31956. ], Material.prototype, "fillMode", null);
  31957. return Material;
  31958. }());
  31959. BABYLON.Material = Material;
  31960. })(BABYLON || (BABYLON = {}));
  31961. //# sourceMappingURL=babylon.material.js.map
  31962. var BABYLON;
  31963. (function (BABYLON) {
  31964. var UniformBuffer = /** @class */ (function () {
  31965. /**
  31966. * Uniform buffer objects.
  31967. *
  31968. * Handles blocks of uniform on the GPU.
  31969. *
  31970. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31971. *
  31972. * For more information, please refer to :
  31973. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31974. */
  31975. function UniformBuffer(engine, data, dynamic) {
  31976. this._engine = engine;
  31977. this._noUBO = !engine.supportsUniformBuffers;
  31978. this._dynamic = dynamic;
  31979. this._data = data || [];
  31980. this._uniformLocations = {};
  31981. this._uniformSizes = {};
  31982. this._uniformLocationPointer = 0;
  31983. this._needSync = false;
  31984. if (this._noUBO) {
  31985. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31986. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31987. this.updateFloat = this._updateFloatForEffect;
  31988. this.updateFloat2 = this._updateFloat2ForEffect;
  31989. this.updateFloat3 = this._updateFloat3ForEffect;
  31990. this.updateFloat4 = this._updateFloat4ForEffect;
  31991. this.updateMatrix = this._updateMatrixForEffect;
  31992. this.updateVector3 = this._updateVector3ForEffect;
  31993. this.updateVector4 = this._updateVector4ForEffect;
  31994. this.updateColor3 = this._updateColor3ForEffect;
  31995. this.updateColor4 = this._updateColor4ForEffect;
  31996. }
  31997. else {
  31998. this._engine._uniformBuffers.push(this);
  31999. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32000. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32001. this.updateFloat = this._updateFloatForUniform;
  32002. this.updateFloat2 = this._updateFloat2ForUniform;
  32003. this.updateFloat3 = this._updateFloat3ForUniform;
  32004. this.updateFloat4 = this._updateFloat4ForUniform;
  32005. this.updateMatrix = this._updateMatrixForUniform;
  32006. this.updateVector3 = this._updateVector3ForUniform;
  32007. this.updateVector4 = this._updateVector4ForUniform;
  32008. this.updateColor3 = this._updateColor3ForUniform;
  32009. this.updateColor4 = this._updateColor4ForUniform;
  32010. }
  32011. }
  32012. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32013. // Properties
  32014. /**
  32015. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32016. * or just falling back on setUniformXXX calls.
  32017. */
  32018. get: function () {
  32019. return !this._noUBO;
  32020. },
  32021. enumerable: true,
  32022. configurable: true
  32023. });
  32024. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32025. /**
  32026. * Indicates if the WebGL underlying uniform buffer is in sync
  32027. * with the javascript cache data.
  32028. */
  32029. get: function () {
  32030. return !this._needSync;
  32031. },
  32032. enumerable: true,
  32033. configurable: true
  32034. });
  32035. /**
  32036. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32037. * Also, a dynamic UniformBuffer will disable cache verification and always
  32038. * update the underlying WebGL uniform buffer to the GPU.
  32039. */
  32040. UniformBuffer.prototype.isDynamic = function () {
  32041. return this._dynamic !== undefined;
  32042. };
  32043. /**
  32044. * The data cache on JS side.
  32045. */
  32046. UniformBuffer.prototype.getData = function () {
  32047. return this._bufferData;
  32048. };
  32049. /**
  32050. * The underlying WebGL Uniform buffer.
  32051. */
  32052. UniformBuffer.prototype.getBuffer = function () {
  32053. return this._buffer;
  32054. };
  32055. /**
  32056. * std140 layout specifies how to align data within an UBO structure.
  32057. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32058. * for specs.
  32059. */
  32060. UniformBuffer.prototype._fillAlignment = function (size) {
  32061. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32062. // and 4x4 matrices
  32063. // TODO : change if other types are used
  32064. var alignment;
  32065. if (size <= 2) {
  32066. alignment = size;
  32067. }
  32068. else {
  32069. alignment = 4;
  32070. }
  32071. if ((this._uniformLocationPointer % alignment) !== 0) {
  32072. var oldPointer = this._uniformLocationPointer;
  32073. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32074. var diff = this._uniformLocationPointer - oldPointer;
  32075. for (var i = 0; i < diff; i++) {
  32076. this._data.push(0);
  32077. }
  32078. }
  32079. };
  32080. /**
  32081. * Adds an uniform in the buffer.
  32082. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32083. * for the layout to be correct !
  32084. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32085. * @param {number|number[]} size Data size, or data directly.
  32086. */
  32087. UniformBuffer.prototype.addUniform = function (name, size) {
  32088. if (this._noUBO) {
  32089. return;
  32090. }
  32091. if (this._uniformLocations[name] !== undefined) {
  32092. // Already existing uniform
  32093. return;
  32094. }
  32095. // This function must be called in the order of the shader layout !
  32096. // size can be the size of the uniform, or data directly
  32097. var data;
  32098. if (size instanceof Array) {
  32099. data = size;
  32100. size = data.length;
  32101. }
  32102. else {
  32103. size = size;
  32104. data = [];
  32105. // Fill with zeros
  32106. for (var i = 0; i < size; i++) {
  32107. data.push(0);
  32108. }
  32109. }
  32110. this._fillAlignment(size);
  32111. this._uniformSizes[name] = size;
  32112. this._uniformLocations[name] = this._uniformLocationPointer;
  32113. this._uniformLocationPointer += size;
  32114. for (var i = 0; i < size; i++) {
  32115. this._data.push(data[i]);
  32116. }
  32117. this._needSync = true;
  32118. };
  32119. /**
  32120. * Wrapper for addUniform.
  32121. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32122. * @param {Matrix} mat A 4x4 matrix.
  32123. */
  32124. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32125. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32126. };
  32127. /**
  32128. * Wrapper for addUniform.
  32129. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32130. * @param {number} x
  32131. * @param {number} y
  32132. */
  32133. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32134. var temp = [x, y];
  32135. this.addUniform(name, temp);
  32136. };
  32137. /**
  32138. * Wrapper for addUniform.
  32139. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32140. * @param {number} x
  32141. * @param {number} y
  32142. * @param {number} z
  32143. */
  32144. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32145. var temp = [x, y, z];
  32146. this.addUniform(name, temp);
  32147. };
  32148. /**
  32149. * Wrapper for addUniform.
  32150. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32151. * @param {Color3} color
  32152. */
  32153. UniformBuffer.prototype.addColor3 = function (name, color) {
  32154. var temp = new Array();
  32155. color.toArray(temp);
  32156. this.addUniform(name, temp);
  32157. };
  32158. /**
  32159. * Wrapper for addUniform.
  32160. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32161. * @param {Color3} color
  32162. * @param {number} alpha
  32163. */
  32164. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32165. var temp = new Array();
  32166. color.toArray(temp);
  32167. temp.push(alpha);
  32168. this.addUniform(name, temp);
  32169. };
  32170. /**
  32171. * Wrapper for addUniform.
  32172. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32173. * @param {Vector3} vector
  32174. */
  32175. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32176. var temp = new Array();
  32177. vector.toArray(temp);
  32178. this.addUniform(name, temp);
  32179. };
  32180. /**
  32181. * Wrapper for addUniform.
  32182. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32183. */
  32184. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32185. this.addUniform(name, 12);
  32186. };
  32187. /**
  32188. * Wrapper for addUniform.
  32189. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32190. */
  32191. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32192. this.addUniform(name, 8);
  32193. };
  32194. /**
  32195. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32196. */
  32197. UniformBuffer.prototype.create = function () {
  32198. if (this._noUBO) {
  32199. return;
  32200. }
  32201. if (this._buffer) {
  32202. return; // nothing to do
  32203. }
  32204. // See spec, alignment must be filled as a vec4
  32205. this._fillAlignment(4);
  32206. this._bufferData = new Float32Array(this._data);
  32207. this._rebuild();
  32208. this._needSync = true;
  32209. };
  32210. UniformBuffer.prototype._rebuild = function () {
  32211. if (this._noUBO) {
  32212. return;
  32213. }
  32214. if (this._dynamic) {
  32215. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32216. }
  32217. else {
  32218. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32219. }
  32220. };
  32221. /**
  32222. * Updates the WebGL Uniform Buffer on the GPU.
  32223. * If the `dynamic` flag is set to true, no cache comparison is done.
  32224. * Otherwise, the buffer will be updated only if the cache differs.
  32225. */
  32226. UniformBuffer.prototype.update = function () {
  32227. if (!this._buffer) {
  32228. this.create();
  32229. return;
  32230. }
  32231. if (!this._dynamic && !this._needSync) {
  32232. return;
  32233. }
  32234. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32235. this._needSync = false;
  32236. };
  32237. /**
  32238. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32239. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32240. * @param {number[]|Float32Array} data Flattened data
  32241. * @param {number} size Size of the data.
  32242. */
  32243. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32244. var location = this._uniformLocations[uniformName];
  32245. if (location === undefined) {
  32246. if (this._buffer) {
  32247. // Cannot add an uniform if the buffer is already created
  32248. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32249. return;
  32250. }
  32251. this.addUniform(uniformName, size);
  32252. location = this._uniformLocations[uniformName];
  32253. }
  32254. if (!this._buffer) {
  32255. this.create();
  32256. }
  32257. if (!this._dynamic) {
  32258. // Cache for static uniform buffers
  32259. var changed = false;
  32260. for (var i = 0; i < size; i++) {
  32261. if (this._bufferData[location + i] !== data[i]) {
  32262. changed = true;
  32263. this._bufferData[location + i] = data[i];
  32264. }
  32265. }
  32266. this._needSync = this._needSync || changed;
  32267. }
  32268. else {
  32269. // No cache for dynamic
  32270. for (var i = 0; i < size; i++) {
  32271. this._bufferData[location + i] = data[i];
  32272. }
  32273. }
  32274. };
  32275. // Update methods
  32276. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32277. // To match std140, matrix must be realigned
  32278. for (var i = 0; i < 3; i++) {
  32279. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32280. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32281. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32282. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32283. }
  32284. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32285. };
  32286. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32287. this._currentEffect.setMatrix3x3(name, matrix);
  32288. };
  32289. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32290. this._currentEffect.setMatrix2x2(name, matrix);
  32291. };
  32292. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32293. // To match std140, matrix must be realigned
  32294. for (var i = 0; i < 2; i++) {
  32295. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32296. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32297. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32298. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32299. }
  32300. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32301. };
  32302. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32303. this._currentEffect.setFloat(name, x);
  32304. };
  32305. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32306. UniformBuffer._tempBuffer[0] = x;
  32307. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32308. };
  32309. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32310. if (suffix === void 0) { suffix = ""; }
  32311. this._currentEffect.setFloat2(name + suffix, x, y);
  32312. };
  32313. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32314. if (suffix === void 0) { suffix = ""; }
  32315. UniformBuffer._tempBuffer[0] = x;
  32316. UniformBuffer._tempBuffer[1] = y;
  32317. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32318. };
  32319. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32320. if (suffix === void 0) { suffix = ""; }
  32321. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32322. };
  32323. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32324. if (suffix === void 0) { suffix = ""; }
  32325. UniformBuffer._tempBuffer[0] = x;
  32326. UniformBuffer._tempBuffer[1] = y;
  32327. UniformBuffer._tempBuffer[2] = z;
  32328. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32329. };
  32330. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32331. if (suffix === void 0) { suffix = ""; }
  32332. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32333. };
  32334. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32335. if (suffix === void 0) { suffix = ""; }
  32336. UniformBuffer._tempBuffer[0] = x;
  32337. UniformBuffer._tempBuffer[1] = y;
  32338. UniformBuffer._tempBuffer[2] = z;
  32339. UniformBuffer._tempBuffer[3] = w;
  32340. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32341. };
  32342. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32343. this._currentEffect.setMatrix(name, mat);
  32344. };
  32345. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32346. this.updateUniform(name, mat.toArray(), 16);
  32347. };
  32348. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32349. this._currentEffect.setVector3(name, vector);
  32350. };
  32351. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32352. vector.toArray(UniformBuffer._tempBuffer);
  32353. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32354. };
  32355. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32356. this._currentEffect.setVector4(name, vector);
  32357. };
  32358. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32359. vector.toArray(UniformBuffer._tempBuffer);
  32360. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32361. };
  32362. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32363. if (suffix === void 0) { suffix = ""; }
  32364. this._currentEffect.setColor3(name + suffix, color);
  32365. };
  32366. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32367. if (suffix === void 0) { suffix = ""; }
  32368. color.toArray(UniformBuffer._tempBuffer);
  32369. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32370. };
  32371. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32372. if (suffix === void 0) { suffix = ""; }
  32373. this._currentEffect.setColor4(name + suffix, color, alpha);
  32374. };
  32375. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32376. if (suffix === void 0) { suffix = ""; }
  32377. color.toArray(UniformBuffer._tempBuffer);
  32378. UniformBuffer._tempBuffer[3] = alpha;
  32379. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32380. };
  32381. /**
  32382. * Sets a sampler uniform on the effect.
  32383. * @param {string} name Name of the sampler.
  32384. * @param {Texture} texture
  32385. */
  32386. UniformBuffer.prototype.setTexture = function (name, texture) {
  32387. this._currentEffect.setTexture(name, texture);
  32388. };
  32389. /**
  32390. * Directly updates the value of the uniform in the cache AND on the GPU.
  32391. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32392. * @param {number[]|Float32Array} data Flattened data
  32393. */
  32394. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32395. this.updateUniform(uniformName, data, data.length);
  32396. this.update();
  32397. };
  32398. /**
  32399. * Binds this uniform buffer to an effect.
  32400. * @param {Effect} effect
  32401. * @param {string} name Name of the uniform block in the shader.
  32402. */
  32403. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32404. this._currentEffect = effect;
  32405. if (this._noUBO || !this._buffer) {
  32406. return;
  32407. }
  32408. effect.bindUniformBuffer(this._buffer, name);
  32409. };
  32410. /**
  32411. * Disposes the uniform buffer.
  32412. */
  32413. UniformBuffer.prototype.dispose = function () {
  32414. if (this._noUBO) {
  32415. return;
  32416. }
  32417. var index = this._engine._uniformBuffers.indexOf(this);
  32418. if (index !== -1) {
  32419. this._engine._uniformBuffers.splice(index, 1);
  32420. }
  32421. if (!this._buffer) {
  32422. return;
  32423. }
  32424. if (this._engine._releaseBuffer(this._buffer)) {
  32425. this._buffer = null;
  32426. }
  32427. };
  32428. // Pool for avoiding memory leaks
  32429. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32430. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32431. return UniformBuffer;
  32432. }());
  32433. BABYLON.UniformBuffer = UniformBuffer;
  32434. })(BABYLON || (BABYLON = {}));
  32435. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32436. var BABYLON;
  32437. (function (BABYLON) {
  32438. var VertexData = /** @class */ (function () {
  32439. function VertexData() {
  32440. }
  32441. VertexData.prototype.set = function (data, kind) {
  32442. switch (kind) {
  32443. case BABYLON.VertexBuffer.PositionKind:
  32444. this.positions = data;
  32445. break;
  32446. case BABYLON.VertexBuffer.NormalKind:
  32447. this.normals = data;
  32448. break;
  32449. case BABYLON.VertexBuffer.TangentKind:
  32450. this.tangents = data;
  32451. break;
  32452. case BABYLON.VertexBuffer.UVKind:
  32453. this.uvs = data;
  32454. break;
  32455. case BABYLON.VertexBuffer.UV2Kind:
  32456. this.uvs2 = data;
  32457. break;
  32458. case BABYLON.VertexBuffer.UV3Kind:
  32459. this.uvs3 = data;
  32460. break;
  32461. case BABYLON.VertexBuffer.UV4Kind:
  32462. this.uvs4 = data;
  32463. break;
  32464. case BABYLON.VertexBuffer.UV5Kind:
  32465. this.uvs5 = data;
  32466. break;
  32467. case BABYLON.VertexBuffer.UV6Kind:
  32468. this.uvs6 = data;
  32469. break;
  32470. case BABYLON.VertexBuffer.ColorKind:
  32471. this.colors = data;
  32472. break;
  32473. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32474. this.matricesIndices = data;
  32475. break;
  32476. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32477. this.matricesWeights = data;
  32478. break;
  32479. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32480. this.matricesIndicesExtra = data;
  32481. break;
  32482. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32483. this.matricesWeightsExtra = data;
  32484. break;
  32485. }
  32486. };
  32487. /**
  32488. * Associates the vertexData to the passed Mesh.
  32489. * Sets it as updatable or not (default `false`).
  32490. * Returns the VertexData.
  32491. */
  32492. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32493. this._applyTo(mesh, updatable);
  32494. return this;
  32495. };
  32496. /**
  32497. * Associates the vertexData to the passed Geometry.
  32498. * Sets it as updatable or not (default `false`).
  32499. * Returns the VertexData.
  32500. */
  32501. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32502. this._applyTo(geometry, updatable);
  32503. return this;
  32504. };
  32505. /**
  32506. * Updates the associated mesh.
  32507. * Returns the VertexData.
  32508. */
  32509. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32510. this._update(mesh);
  32511. return this;
  32512. };
  32513. /**
  32514. * Updates the associated geometry.
  32515. * Returns the VertexData.
  32516. */
  32517. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32518. this._update(geometry);
  32519. return this;
  32520. };
  32521. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32522. if (updatable === void 0) { updatable = false; }
  32523. if (this.positions) {
  32524. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32525. }
  32526. if (this.normals) {
  32527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32528. }
  32529. if (this.tangents) {
  32530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32531. }
  32532. if (this.uvs) {
  32533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32534. }
  32535. if (this.uvs2) {
  32536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32537. }
  32538. if (this.uvs3) {
  32539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32540. }
  32541. if (this.uvs4) {
  32542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32543. }
  32544. if (this.uvs5) {
  32545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32546. }
  32547. if (this.uvs6) {
  32548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32549. }
  32550. if (this.colors) {
  32551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32552. }
  32553. if (this.matricesIndices) {
  32554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32555. }
  32556. if (this.matricesWeights) {
  32557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32558. }
  32559. if (this.matricesIndicesExtra) {
  32560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32561. }
  32562. if (this.matricesWeightsExtra) {
  32563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32564. }
  32565. if (this.indices) {
  32566. meshOrGeometry.setIndices(this.indices, null, updatable);
  32567. }
  32568. return this;
  32569. };
  32570. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32571. if (this.positions) {
  32572. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32573. }
  32574. if (this.normals) {
  32575. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32576. }
  32577. if (this.tangents) {
  32578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32579. }
  32580. if (this.uvs) {
  32581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32582. }
  32583. if (this.uvs2) {
  32584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32585. }
  32586. if (this.uvs3) {
  32587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32588. }
  32589. if (this.uvs4) {
  32590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32591. }
  32592. if (this.uvs5) {
  32593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32594. }
  32595. if (this.uvs6) {
  32596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32597. }
  32598. if (this.colors) {
  32599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32600. }
  32601. if (this.matricesIndices) {
  32602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32603. }
  32604. if (this.matricesWeights) {
  32605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32606. }
  32607. if (this.matricesIndicesExtra) {
  32608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32609. }
  32610. if (this.matricesWeightsExtra) {
  32611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32612. }
  32613. if (this.indices) {
  32614. meshOrGeometry.setIndices(this.indices, null);
  32615. }
  32616. return this;
  32617. };
  32618. /**
  32619. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32620. * Returns the VertexData.
  32621. */
  32622. VertexData.prototype.transform = function (matrix) {
  32623. var transformed = BABYLON.Vector3.Zero();
  32624. var index;
  32625. if (this.positions) {
  32626. var position = BABYLON.Vector3.Zero();
  32627. for (index = 0; index < this.positions.length; index += 3) {
  32628. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32629. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32630. this.positions[index] = transformed.x;
  32631. this.positions[index + 1] = transformed.y;
  32632. this.positions[index + 2] = transformed.z;
  32633. }
  32634. }
  32635. if (this.normals) {
  32636. var normal = BABYLON.Vector3.Zero();
  32637. for (index = 0; index < this.normals.length; index += 3) {
  32638. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32639. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32640. this.normals[index] = transformed.x;
  32641. this.normals[index + 1] = transformed.y;
  32642. this.normals[index + 2] = transformed.z;
  32643. }
  32644. }
  32645. if (this.tangents) {
  32646. var tangent = BABYLON.Vector4.Zero();
  32647. var tangentTransformed = BABYLON.Vector4.Zero();
  32648. for (index = 0; index < this.tangents.length; index += 4) {
  32649. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32650. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32651. this.tangents[index] = tangentTransformed.x;
  32652. this.tangents[index + 1] = tangentTransformed.y;
  32653. this.tangents[index + 2] = tangentTransformed.z;
  32654. this.tangents[index + 3] = tangentTransformed.w;
  32655. }
  32656. }
  32657. return this;
  32658. };
  32659. /**
  32660. * Merges the passed VertexData into the current one.
  32661. * Returns the modified VertexData.
  32662. */
  32663. VertexData.prototype.merge = function (other) {
  32664. this._validate();
  32665. other._validate();
  32666. if (!this.normals !== !other.normals ||
  32667. !this.tangents !== !other.tangents ||
  32668. !this.uvs !== !other.uvs ||
  32669. !this.uvs2 !== !other.uvs2 ||
  32670. !this.uvs3 !== !other.uvs3 ||
  32671. !this.uvs4 !== !other.uvs4 ||
  32672. !this.uvs5 !== !other.uvs5 ||
  32673. !this.uvs6 !== !other.uvs6 ||
  32674. !this.colors !== !other.colors ||
  32675. !this.matricesIndices !== !other.matricesIndices ||
  32676. !this.matricesWeights !== !other.matricesWeights ||
  32677. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32678. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32679. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32680. }
  32681. if (other.indices) {
  32682. if (!this.indices) {
  32683. this.indices = [];
  32684. }
  32685. var offset = this.positions ? this.positions.length / 3 : 0;
  32686. for (var index = 0; index < other.indices.length; index++) {
  32687. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32688. this.indices.push(other.indices[index] + offset);
  32689. }
  32690. }
  32691. this.positions = this._mergeElement(this.positions, other.positions);
  32692. this.normals = this._mergeElement(this.normals, other.normals);
  32693. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32694. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32695. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32696. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32697. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32698. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32699. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32700. this.colors = this._mergeElement(this.colors, other.colors);
  32701. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32702. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32703. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32704. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32705. return this;
  32706. };
  32707. VertexData.prototype._mergeElement = function (source, other) {
  32708. if (!source) {
  32709. return other;
  32710. }
  32711. if (!other) {
  32712. return source;
  32713. }
  32714. var len = other.length + source.length;
  32715. var isSrcTypedArray = source instanceof Float32Array;
  32716. var isOthTypedArray = other instanceof Float32Array;
  32717. // use non-loop method when the source is Float32Array
  32718. if (isSrcTypedArray) {
  32719. var ret32 = new Float32Array(len);
  32720. ret32.set(source);
  32721. ret32.set(other, source.length);
  32722. return ret32;
  32723. // source is number[], when other is also use concat
  32724. }
  32725. else if (!isOthTypedArray) {
  32726. return source.concat(other);
  32727. // source is a number[], but other is a Float32Array, loop required
  32728. }
  32729. else {
  32730. var ret = source.slice(0); // copy source to a separate array
  32731. for (var i = 0, len = other.length; i < len; i++) {
  32732. ret.push(other[i]);
  32733. }
  32734. return ret;
  32735. }
  32736. };
  32737. VertexData.prototype._validate = function () {
  32738. if (!this.positions) {
  32739. throw new Error("Positions are required");
  32740. }
  32741. var getElementCount = function (kind, values) {
  32742. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32743. if ((values.length % stride) !== 0) {
  32744. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32745. }
  32746. return values.length / stride;
  32747. };
  32748. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32749. var validateElementCount = function (kind, values) {
  32750. var elementCount = getElementCount(kind, values);
  32751. if (elementCount !== positionsElementCount) {
  32752. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32753. }
  32754. };
  32755. if (this.normals)
  32756. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32757. if (this.tangents)
  32758. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32759. if (this.uvs)
  32760. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32761. if (this.uvs2)
  32762. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32763. if (this.uvs3)
  32764. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32765. if (this.uvs4)
  32766. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32767. if (this.uvs5)
  32768. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32769. if (this.uvs6)
  32770. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32771. if (this.colors)
  32772. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32773. if (this.matricesIndices)
  32774. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32775. if (this.matricesWeights)
  32776. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32777. if (this.matricesIndicesExtra)
  32778. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32779. if (this.matricesWeightsExtra)
  32780. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32781. };
  32782. /**
  32783. * Serializes the VertexData.
  32784. * Returns a serialized object.
  32785. */
  32786. VertexData.prototype.serialize = function () {
  32787. var serializationObject = this.serialize();
  32788. if (this.positions) {
  32789. serializationObject.positions = this.positions;
  32790. }
  32791. if (this.normals) {
  32792. serializationObject.normals = this.normals;
  32793. }
  32794. if (this.tangents) {
  32795. serializationObject.tangents = this.tangents;
  32796. }
  32797. if (this.uvs) {
  32798. serializationObject.uvs = this.uvs;
  32799. }
  32800. if (this.uvs2) {
  32801. serializationObject.uvs2 = this.uvs2;
  32802. }
  32803. if (this.uvs3) {
  32804. serializationObject.uvs3 = this.uvs3;
  32805. }
  32806. if (this.uvs4) {
  32807. serializationObject.uvs4 = this.uvs4;
  32808. }
  32809. if (this.uvs5) {
  32810. serializationObject.uvs5 = this.uvs5;
  32811. }
  32812. if (this.uvs6) {
  32813. serializationObject.uvs6 = this.uvs6;
  32814. }
  32815. if (this.colors) {
  32816. serializationObject.colors = this.colors;
  32817. }
  32818. if (this.matricesIndices) {
  32819. serializationObject.matricesIndices = this.matricesIndices;
  32820. serializationObject.matricesIndices._isExpanded = true;
  32821. }
  32822. if (this.matricesWeights) {
  32823. serializationObject.matricesWeights = this.matricesWeights;
  32824. }
  32825. if (this.matricesIndicesExtra) {
  32826. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32827. serializationObject.matricesIndicesExtra._isExpanded = true;
  32828. }
  32829. if (this.matricesWeightsExtra) {
  32830. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32831. }
  32832. serializationObject.indices = this.indices;
  32833. return serializationObject;
  32834. };
  32835. // Statics
  32836. /**
  32837. * Returns the object VertexData associated to the passed mesh.
  32838. */
  32839. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32840. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32841. };
  32842. /**
  32843. * Returns the object VertexData associated to the passed geometry.
  32844. */
  32845. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32846. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32847. };
  32848. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32849. var result = new VertexData();
  32850. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32851. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32852. }
  32853. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32854. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32855. }
  32856. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32857. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32858. }
  32859. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32860. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32861. }
  32862. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32863. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32864. }
  32865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32866. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32867. }
  32868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32869. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32870. }
  32871. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32872. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32873. }
  32874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32875. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32876. }
  32877. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32878. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32879. }
  32880. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32881. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32882. }
  32883. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32884. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32885. }
  32886. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32887. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32888. }
  32889. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32890. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32891. }
  32892. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32893. return result;
  32894. };
  32895. /**
  32896. * Creates the vertexData of the Ribbon.
  32897. */
  32898. VertexData.CreateRibbon = function (options) {
  32899. var pathArray = options.pathArray;
  32900. var closeArray = options.closeArray || false;
  32901. var closePath = options.closePath || false;
  32902. var invertUV = options.invertUV || false;
  32903. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32904. var offset = options.offset || defaultOffset;
  32905. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32906. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32907. var customUV = options.uvs;
  32908. var customColors = options.colors;
  32909. var positions = [];
  32910. var indices = [];
  32911. var normals = [];
  32912. var uvs = [];
  32913. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32914. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32915. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32916. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32917. var minlg; // minimal length among all paths from pathArray
  32918. var lg = []; // array of path lengths : nb of vertex per path
  32919. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32920. var p; // path iterator
  32921. var i; // point iterator
  32922. var j; // point iterator
  32923. // if single path in pathArray
  32924. if (pathArray.length < 2) {
  32925. var ar1 = [];
  32926. var ar2 = [];
  32927. for (i = 0; i < pathArray[0].length - offset; i++) {
  32928. ar1.push(pathArray[0][i]);
  32929. ar2.push(pathArray[0][i + offset]);
  32930. }
  32931. pathArray = [ar1, ar2];
  32932. }
  32933. // positions and horizontal distances (u)
  32934. var idc = 0;
  32935. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32936. var path;
  32937. var l;
  32938. minlg = pathArray[0].length;
  32939. var vectlg;
  32940. var dist;
  32941. for (p = 0; p < pathArray.length; p++) {
  32942. uTotalDistance[p] = 0;
  32943. us[p] = [0];
  32944. path = pathArray[p];
  32945. l = path.length;
  32946. minlg = (minlg < l) ? minlg : l;
  32947. j = 0;
  32948. while (j < l) {
  32949. positions.push(path[j].x, path[j].y, path[j].z);
  32950. if (j > 0) {
  32951. vectlg = path[j].subtract(path[j - 1]).length();
  32952. dist = vectlg + uTotalDistance[p];
  32953. us[p].push(dist);
  32954. uTotalDistance[p] = dist;
  32955. }
  32956. j++;
  32957. }
  32958. if (closePath) {
  32959. j--;
  32960. positions.push(path[0].x, path[0].y, path[0].z);
  32961. vectlg = path[j].subtract(path[0]).length();
  32962. dist = vectlg + uTotalDistance[p];
  32963. us[p].push(dist);
  32964. uTotalDistance[p] = dist;
  32965. }
  32966. lg[p] = l + closePathCorr;
  32967. idx[p] = idc;
  32968. idc += (l + closePathCorr);
  32969. }
  32970. // vertical distances (v)
  32971. var path1;
  32972. var path2;
  32973. var vertex1 = null;
  32974. var vertex2 = null;
  32975. for (i = 0; i < minlg + closePathCorr; i++) {
  32976. vTotalDistance[i] = 0;
  32977. vs[i] = [0];
  32978. for (p = 0; p < pathArray.length - 1; p++) {
  32979. path1 = pathArray[p];
  32980. path2 = pathArray[p + 1];
  32981. if (i === minlg) {
  32982. vertex1 = path1[0];
  32983. vertex2 = path2[0];
  32984. }
  32985. else {
  32986. vertex1 = path1[i];
  32987. vertex2 = path2[i];
  32988. }
  32989. vectlg = vertex2.subtract(vertex1).length();
  32990. dist = vectlg + vTotalDistance[i];
  32991. vs[i].push(dist);
  32992. vTotalDistance[i] = dist;
  32993. }
  32994. if (closeArray && vertex2 && vertex1) {
  32995. path1 = pathArray[p];
  32996. path2 = pathArray[0];
  32997. if (i === minlg) {
  32998. vertex2 = path2[0];
  32999. }
  33000. vectlg = vertex2.subtract(vertex1).length();
  33001. dist = vectlg + vTotalDistance[i];
  33002. vTotalDistance[i] = dist;
  33003. }
  33004. }
  33005. // uvs
  33006. var u;
  33007. var v;
  33008. if (customUV) {
  33009. for (p = 0; p < customUV.length; p++) {
  33010. uvs.push(customUV[p].x, customUV[p].y);
  33011. }
  33012. }
  33013. else {
  33014. for (p = 0; p < pathArray.length; p++) {
  33015. for (i = 0; i < minlg + closePathCorr; i++) {
  33016. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33017. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33018. if (invertUV) {
  33019. uvs.push(v, u);
  33020. }
  33021. else {
  33022. uvs.push(u, v);
  33023. }
  33024. }
  33025. }
  33026. }
  33027. // indices
  33028. p = 0; // path index
  33029. var pi = 0; // positions array index
  33030. var l1 = lg[p] - 1; // path1 length
  33031. var l2 = lg[p + 1] - 1; // path2 length
  33032. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33033. var shft = idx[1] - idx[0]; // shift
  33034. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33035. while (pi <= min && p < path1nb) {
  33036. // 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
  33037. indices.push(pi, pi + shft, pi + 1);
  33038. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33039. pi += 1;
  33040. if (pi === min) {
  33041. p++;
  33042. if (p === lg.length - 1) {
  33043. shft = idx[0] - idx[p];
  33044. l1 = lg[p] - 1;
  33045. l2 = lg[0] - 1;
  33046. }
  33047. else {
  33048. shft = idx[p + 1] - idx[p];
  33049. l1 = lg[p] - 1;
  33050. l2 = lg[p + 1] - 1;
  33051. }
  33052. pi = idx[p];
  33053. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33054. }
  33055. }
  33056. // normals
  33057. VertexData.ComputeNormals(positions, indices, normals);
  33058. if (closePath) {
  33059. var indexFirst = 0;
  33060. var indexLast = 0;
  33061. for (p = 0; p < pathArray.length; p++) {
  33062. indexFirst = idx[p] * 3;
  33063. if (p + 1 < pathArray.length) {
  33064. indexLast = (idx[p + 1] - 1) * 3;
  33065. }
  33066. else {
  33067. indexLast = normals.length - 3;
  33068. }
  33069. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33070. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33071. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33072. normals[indexLast] = normals[indexFirst];
  33073. normals[indexLast + 1] = normals[indexFirst + 1];
  33074. normals[indexLast + 2] = normals[indexFirst + 2];
  33075. }
  33076. }
  33077. // sides
  33078. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33079. // Colors
  33080. var colors = null;
  33081. if (customColors) {
  33082. colors = new Float32Array(customColors.length * 4);
  33083. for (var c = 0; c < customColors.length; c++) {
  33084. colors[c * 4] = customColors[c].r;
  33085. colors[c * 4 + 1] = customColors[c].g;
  33086. colors[c * 4 + 2] = customColors[c].b;
  33087. colors[c * 4 + 3] = customColors[c].a;
  33088. }
  33089. }
  33090. // Result
  33091. var vertexData = new VertexData();
  33092. var positions32 = new Float32Array(positions);
  33093. var normals32 = new Float32Array(normals);
  33094. var uvs32 = new Float32Array(uvs);
  33095. vertexData.indices = indices;
  33096. vertexData.positions = positions32;
  33097. vertexData.normals = normals32;
  33098. vertexData.uvs = uvs32;
  33099. if (colors) {
  33100. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33101. }
  33102. if (closePath) {
  33103. vertexData._idx = idx;
  33104. }
  33105. return vertexData;
  33106. };
  33107. /**
  33108. * Creates the VertexData of the Box.
  33109. */
  33110. VertexData.CreateBox = function (options) {
  33111. var normalsSource = [
  33112. new BABYLON.Vector3(0, 0, 1),
  33113. new BABYLON.Vector3(0, 0, -1),
  33114. new BABYLON.Vector3(1, 0, 0),
  33115. new BABYLON.Vector3(-1, 0, 0),
  33116. new BABYLON.Vector3(0, 1, 0),
  33117. new BABYLON.Vector3(0, -1, 0)
  33118. ];
  33119. var indices = [];
  33120. var positions = [];
  33121. var normals = [];
  33122. var uvs = [];
  33123. var width = options.width || options.size || 1;
  33124. var height = options.height || options.size || 1;
  33125. var depth = options.depth || options.size || 1;
  33126. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33127. var faceUV = options.faceUV || new Array(6);
  33128. var faceColors = options.faceColors;
  33129. var colors = [];
  33130. // default face colors and UV if undefined
  33131. for (var f = 0; f < 6; f++) {
  33132. if (faceUV[f] === undefined) {
  33133. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33134. }
  33135. if (faceColors && faceColors[f] === undefined) {
  33136. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33137. }
  33138. }
  33139. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33140. // Create each face in turn.
  33141. for (var index = 0; index < normalsSource.length; index++) {
  33142. var normal = normalsSource[index];
  33143. // Get two vectors perpendicular to the face normal and to each other.
  33144. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33145. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33146. // Six indices (two triangles) per face.
  33147. var verticesLength = positions.length / 3;
  33148. indices.push(verticesLength);
  33149. indices.push(verticesLength + 1);
  33150. indices.push(verticesLength + 2);
  33151. indices.push(verticesLength);
  33152. indices.push(verticesLength + 2);
  33153. indices.push(verticesLength + 3);
  33154. // Four vertices per face.
  33155. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33156. positions.push(vertex.x, vertex.y, vertex.z);
  33157. normals.push(normal.x, normal.y, normal.z);
  33158. uvs.push(faceUV[index].z, faceUV[index].w);
  33159. if (faceColors) {
  33160. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33161. }
  33162. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33163. positions.push(vertex.x, vertex.y, vertex.z);
  33164. normals.push(normal.x, normal.y, normal.z);
  33165. uvs.push(faceUV[index].x, faceUV[index].w);
  33166. if (faceColors) {
  33167. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33168. }
  33169. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33170. positions.push(vertex.x, vertex.y, vertex.z);
  33171. normals.push(normal.x, normal.y, normal.z);
  33172. uvs.push(faceUV[index].x, faceUV[index].y);
  33173. if (faceColors) {
  33174. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33175. }
  33176. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33177. positions.push(vertex.x, vertex.y, vertex.z);
  33178. normals.push(normal.x, normal.y, normal.z);
  33179. uvs.push(faceUV[index].z, faceUV[index].y);
  33180. if (faceColors) {
  33181. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33182. }
  33183. }
  33184. // sides
  33185. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33186. // Result
  33187. var vertexData = new VertexData();
  33188. vertexData.indices = indices;
  33189. vertexData.positions = positions;
  33190. vertexData.normals = normals;
  33191. vertexData.uvs = uvs;
  33192. if (faceColors) {
  33193. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33194. vertexData.colors = totalColors;
  33195. }
  33196. return vertexData;
  33197. };
  33198. /**
  33199. * Creates the VertexData of the Sphere.
  33200. */
  33201. VertexData.CreateSphere = function (options) {
  33202. var segments = options.segments || 32;
  33203. var diameterX = options.diameterX || options.diameter || 1;
  33204. var diameterY = options.diameterY || options.diameter || 1;
  33205. var diameterZ = options.diameterZ || options.diameter || 1;
  33206. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33207. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33208. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33209. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33210. var totalZRotationSteps = 2 + segments;
  33211. var totalYRotationSteps = 2 * totalZRotationSteps;
  33212. var indices = [];
  33213. var positions = [];
  33214. var normals = [];
  33215. var uvs = [];
  33216. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33217. var normalizedZ = zRotationStep / totalZRotationSteps;
  33218. var angleZ = normalizedZ * Math.PI * slice;
  33219. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33220. var normalizedY = yRotationStep / totalYRotationSteps;
  33221. var angleY = normalizedY * Math.PI * 2 * arc;
  33222. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33223. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33224. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33225. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33226. var vertex = complete.multiply(radius);
  33227. var normal = complete.divide(radius).normalize();
  33228. positions.push(vertex.x, vertex.y, vertex.z);
  33229. normals.push(normal.x, normal.y, normal.z);
  33230. uvs.push(normalizedY, normalizedZ);
  33231. }
  33232. if (zRotationStep > 0) {
  33233. var verticesCount = positions.length / 3;
  33234. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33235. indices.push((firstIndex));
  33236. indices.push((firstIndex + 1));
  33237. indices.push(firstIndex + totalYRotationSteps + 1);
  33238. indices.push((firstIndex + totalYRotationSteps + 1));
  33239. indices.push((firstIndex + 1));
  33240. indices.push((firstIndex + totalYRotationSteps + 2));
  33241. }
  33242. }
  33243. }
  33244. // Sides
  33245. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33246. // Result
  33247. var vertexData = new VertexData();
  33248. vertexData.indices = indices;
  33249. vertexData.positions = positions;
  33250. vertexData.normals = normals;
  33251. vertexData.uvs = uvs;
  33252. return vertexData;
  33253. };
  33254. /**
  33255. * Creates the VertexData of the Cylinder or Cone.
  33256. */
  33257. VertexData.CreateCylinder = function (options) {
  33258. var height = options.height || 2;
  33259. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33260. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33261. var tessellation = options.tessellation || 24;
  33262. var subdivisions = options.subdivisions || 1;
  33263. var hasRings = options.hasRings ? true : false;
  33264. var enclose = options.enclose ? true : false;
  33265. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33266. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33267. var faceUV = options.faceUV || new Array(3);
  33268. var faceColors = options.faceColors;
  33269. // default face colors and UV if undefined
  33270. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33271. var ringNb = (hasRings) ? subdivisions : 1;
  33272. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33273. var f;
  33274. for (f = 0; f < surfaceNb; f++) {
  33275. if (faceColors && faceColors[f] === undefined) {
  33276. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33277. }
  33278. }
  33279. for (f = 0; f < surfaceNb; f++) {
  33280. if (faceUV && faceUV[f] === undefined) {
  33281. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33282. }
  33283. }
  33284. var indices = new Array();
  33285. var positions = new Array();
  33286. var normals = new Array();
  33287. var uvs = new Array();
  33288. var colors = new Array();
  33289. var angle_step = Math.PI * 2 * arc / tessellation;
  33290. var angle;
  33291. var h;
  33292. var radius;
  33293. var tan = (diameterBottom - diameterTop) / 2 / height;
  33294. var ringVertex = BABYLON.Vector3.Zero();
  33295. var ringNormal = BABYLON.Vector3.Zero();
  33296. var ringFirstVertex = BABYLON.Vector3.Zero();
  33297. var ringFirstNormal = BABYLON.Vector3.Zero();
  33298. var quadNormal = BABYLON.Vector3.Zero();
  33299. var Y = BABYLON.Axis.Y;
  33300. // positions, normals, uvs
  33301. var i;
  33302. var j;
  33303. var r;
  33304. var ringIdx = 1;
  33305. var s = 1; // surface index
  33306. var cs = 0;
  33307. var v = 0;
  33308. for (i = 0; i <= subdivisions; i++) {
  33309. h = i / subdivisions;
  33310. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33311. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33312. for (r = 0; r < ringIdx; r++) {
  33313. if (hasRings) {
  33314. s += r;
  33315. }
  33316. if (enclose) {
  33317. s += 2 * r;
  33318. }
  33319. for (j = 0; j <= tessellation; j++) {
  33320. angle = j * angle_step;
  33321. // position
  33322. ringVertex.x = Math.cos(-angle) * radius;
  33323. ringVertex.y = -height / 2 + h * height;
  33324. ringVertex.z = Math.sin(-angle) * radius;
  33325. // normal
  33326. if (diameterTop === 0 && i === subdivisions) {
  33327. // if no top cap, reuse former normals
  33328. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33329. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33330. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33331. }
  33332. else {
  33333. ringNormal.x = ringVertex.x;
  33334. ringNormal.z = ringVertex.z;
  33335. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33336. ringNormal.normalize();
  33337. }
  33338. // keep first ring vertex values for enclose
  33339. if (j === 0) {
  33340. ringFirstVertex.copyFrom(ringVertex);
  33341. ringFirstNormal.copyFrom(ringNormal);
  33342. }
  33343. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33344. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33345. if (hasRings) {
  33346. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33347. }
  33348. else {
  33349. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33350. }
  33351. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33352. if (faceColors) {
  33353. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33354. }
  33355. }
  33356. // if enclose, add four vertices and their dedicated normals
  33357. if (arc !== 1 && enclose) {
  33358. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33359. positions.push(0, ringVertex.y, 0);
  33360. positions.push(0, ringVertex.y, 0);
  33361. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33362. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33363. quadNormal.normalize();
  33364. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33365. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33366. quadNormal.normalize();
  33367. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33368. if (hasRings) {
  33369. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33370. }
  33371. else {
  33372. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33373. }
  33374. uvs.push(faceUV[s + 1].x, v);
  33375. uvs.push(faceUV[s + 1].z, v);
  33376. if (hasRings) {
  33377. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33378. }
  33379. else {
  33380. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33381. }
  33382. uvs.push(faceUV[s + 2].x, v);
  33383. uvs.push(faceUV[s + 2].z, v);
  33384. if (faceColors) {
  33385. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33386. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33387. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33388. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33389. }
  33390. }
  33391. if (cs !== s) {
  33392. cs = s;
  33393. }
  33394. }
  33395. }
  33396. // indices
  33397. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33398. var s;
  33399. i = 0;
  33400. for (s = 0; s < subdivisions; s++) {
  33401. var i0 = 0;
  33402. var i1 = 0;
  33403. var i2 = 0;
  33404. var i3 = 0;
  33405. for (j = 0; j < tessellation; j++) {
  33406. i0 = i * (e + 1) + j;
  33407. i1 = (i + 1) * (e + 1) + j;
  33408. i2 = i * (e + 1) + (j + 1);
  33409. i3 = (i + 1) * (e + 1) + (j + 1);
  33410. indices.push(i0, i1, i2);
  33411. indices.push(i3, i2, i1);
  33412. }
  33413. if (arc !== 1 && enclose) {
  33414. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33415. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33416. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33417. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33418. }
  33419. i = (hasRings) ? (i + 2) : (i + 1);
  33420. }
  33421. // Caps
  33422. var createCylinderCap = function (isTop) {
  33423. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33424. if (radius === 0) {
  33425. return;
  33426. }
  33427. // Cap positions, normals & uvs
  33428. var angle;
  33429. var circleVector;
  33430. var i;
  33431. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33432. var c = null;
  33433. if (faceColors) {
  33434. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33435. }
  33436. // cap center
  33437. var vbase = positions.length / 3;
  33438. var offset = isTop ? height / 2 : -height / 2;
  33439. var center = new BABYLON.Vector3(0, offset, 0);
  33440. positions.push(center.x, center.y, center.z);
  33441. normals.push(0, isTop ? 1 : -1, 0);
  33442. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33443. if (c) {
  33444. colors.push(c.r, c.g, c.b, c.a);
  33445. }
  33446. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33447. for (i = 0; i <= tessellation; i++) {
  33448. angle = Math.PI * 2 * i * arc / tessellation;
  33449. var cos = Math.cos(-angle);
  33450. var sin = Math.sin(-angle);
  33451. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33452. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33453. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33454. normals.push(0, isTop ? 1 : -1, 0);
  33455. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33456. if (c) {
  33457. colors.push(c.r, c.g, c.b, c.a);
  33458. }
  33459. }
  33460. // Cap indices
  33461. for (i = 0; i < tessellation; i++) {
  33462. if (!isTop) {
  33463. indices.push(vbase);
  33464. indices.push(vbase + (i + 1));
  33465. indices.push(vbase + (i + 2));
  33466. }
  33467. else {
  33468. indices.push(vbase);
  33469. indices.push(vbase + (i + 2));
  33470. indices.push(vbase + (i + 1));
  33471. }
  33472. }
  33473. };
  33474. // add caps to geometry
  33475. createCylinderCap(false);
  33476. createCylinderCap(true);
  33477. // Sides
  33478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33479. var vertexData = new VertexData();
  33480. vertexData.indices = indices;
  33481. vertexData.positions = positions;
  33482. vertexData.normals = normals;
  33483. vertexData.uvs = uvs;
  33484. if (faceColors) {
  33485. vertexData.colors = colors;
  33486. }
  33487. return vertexData;
  33488. };
  33489. /**
  33490. * Creates the VertexData of the Torus.
  33491. */
  33492. VertexData.CreateTorus = function (options) {
  33493. var indices = [];
  33494. var positions = [];
  33495. var normals = [];
  33496. var uvs = [];
  33497. var diameter = options.diameter || 1;
  33498. var thickness = options.thickness || 0.5;
  33499. var tessellation = options.tessellation || 16;
  33500. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33501. var stride = tessellation + 1;
  33502. for (var i = 0; i <= tessellation; i++) {
  33503. var u = i / tessellation;
  33504. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33505. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33506. for (var j = 0; j <= tessellation; j++) {
  33507. var v = 1 - j / tessellation;
  33508. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33509. var dx = Math.cos(innerAngle);
  33510. var dy = Math.sin(innerAngle);
  33511. // Create a vertex.
  33512. var normal = new BABYLON.Vector3(dx, dy, 0);
  33513. var position = normal.scale(thickness / 2);
  33514. var textureCoordinate = new BABYLON.Vector2(u, v);
  33515. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33516. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33517. positions.push(position.x, position.y, position.z);
  33518. normals.push(normal.x, normal.y, normal.z);
  33519. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33520. // And create indices for two triangles.
  33521. var nextI = (i + 1) % stride;
  33522. var nextJ = (j + 1) % stride;
  33523. indices.push(i * stride + j);
  33524. indices.push(i * stride + nextJ);
  33525. indices.push(nextI * stride + j);
  33526. indices.push(i * stride + nextJ);
  33527. indices.push(nextI * stride + nextJ);
  33528. indices.push(nextI * stride + j);
  33529. }
  33530. }
  33531. // Sides
  33532. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33533. // Result
  33534. var vertexData = new VertexData();
  33535. vertexData.indices = indices;
  33536. vertexData.positions = positions;
  33537. vertexData.normals = normals;
  33538. vertexData.uvs = uvs;
  33539. return vertexData;
  33540. };
  33541. /**
  33542. * Creates the VertexData of the LineSystem.
  33543. */
  33544. VertexData.CreateLineSystem = function (options) {
  33545. var indices = [];
  33546. var positions = [];
  33547. var lines = options.lines;
  33548. var colors = options.colors;
  33549. var vertexColors = [];
  33550. var idx = 0;
  33551. for (var l = 0; l < lines.length; l++) {
  33552. var points = lines[l];
  33553. for (var index = 0; index < points.length; index++) {
  33554. positions.push(points[index].x, points[index].y, points[index].z);
  33555. if (colors) {
  33556. var color = colors[l];
  33557. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33558. }
  33559. if (index > 0) {
  33560. indices.push(idx - 1);
  33561. indices.push(idx);
  33562. }
  33563. idx++;
  33564. }
  33565. }
  33566. var vertexData = new VertexData();
  33567. vertexData.indices = indices;
  33568. vertexData.positions = positions;
  33569. if (colors) {
  33570. vertexData.colors = vertexColors;
  33571. }
  33572. return vertexData;
  33573. };
  33574. /**
  33575. * Create the VertexData of the DashedLines.
  33576. */
  33577. VertexData.CreateDashedLines = function (options) {
  33578. var dashSize = options.dashSize || 3;
  33579. var gapSize = options.gapSize || 1;
  33580. var dashNb = options.dashNb || 200;
  33581. var points = options.points;
  33582. var positions = new Array();
  33583. var indices = new Array();
  33584. var curvect = BABYLON.Vector3.Zero();
  33585. var lg = 0;
  33586. var nb = 0;
  33587. var shft = 0;
  33588. var dashshft = 0;
  33589. var curshft = 0;
  33590. var idx = 0;
  33591. var i = 0;
  33592. for (i = 0; i < points.length - 1; i++) {
  33593. points[i + 1].subtractToRef(points[i], curvect);
  33594. lg += curvect.length();
  33595. }
  33596. shft = lg / dashNb;
  33597. dashshft = dashSize * shft / (dashSize + gapSize);
  33598. for (i = 0; i < points.length - 1; i++) {
  33599. points[i + 1].subtractToRef(points[i], curvect);
  33600. nb = Math.floor(curvect.length() / shft);
  33601. curvect.normalize();
  33602. for (var j = 0; j < nb; j++) {
  33603. curshft = shft * j;
  33604. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33605. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33606. indices.push(idx, idx + 1);
  33607. idx += 2;
  33608. }
  33609. }
  33610. // Result
  33611. var vertexData = new VertexData();
  33612. vertexData.positions = positions;
  33613. vertexData.indices = indices;
  33614. return vertexData;
  33615. };
  33616. /**
  33617. * Creates the VertexData of the Ground.
  33618. */
  33619. VertexData.CreateGround = function (options) {
  33620. var indices = [];
  33621. var positions = [];
  33622. var normals = [];
  33623. var uvs = [];
  33624. var row, col;
  33625. var width = options.width || 1;
  33626. var height = options.height || 1;
  33627. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33628. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33629. for (row = 0; row <= subdivisionsY; row++) {
  33630. for (col = 0; col <= subdivisionsX; col++) {
  33631. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33632. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33633. positions.push(position.x, position.y, position.z);
  33634. normals.push(normal.x, normal.y, normal.z);
  33635. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33636. }
  33637. }
  33638. for (row = 0; row < subdivisionsY; row++) {
  33639. for (col = 0; col < subdivisionsX; col++) {
  33640. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33641. indices.push(col + 1 + row * (subdivisionsX + 1));
  33642. indices.push(col + row * (subdivisionsX + 1));
  33643. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33644. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33645. indices.push(col + row * (subdivisionsX + 1));
  33646. }
  33647. }
  33648. // Result
  33649. var vertexData = new VertexData();
  33650. vertexData.indices = indices;
  33651. vertexData.positions = positions;
  33652. vertexData.normals = normals;
  33653. vertexData.uvs = uvs;
  33654. return vertexData;
  33655. };
  33656. /**
  33657. * Creates the VertexData of the TiledGround.
  33658. */
  33659. VertexData.CreateTiledGround = function (options) {
  33660. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33661. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33662. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33663. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33664. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33665. var precision = options.precision || { w: 1, h: 1 };
  33666. var indices = new Array();
  33667. var positions = new Array();
  33668. var normals = new Array();
  33669. var uvs = new Array();
  33670. var row, col, tileRow, tileCol;
  33671. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33672. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33673. precision.w = (precision.w < 1) ? 1 : precision.w;
  33674. precision.h = (precision.h < 1) ? 1 : precision.h;
  33675. var tileSize = {
  33676. 'w': (xmax - xmin) / subdivisions.w,
  33677. 'h': (zmax - zmin) / subdivisions.h
  33678. };
  33679. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33680. // Indices
  33681. var base = positions.length / 3;
  33682. var rowLength = precision.w + 1;
  33683. for (row = 0; row < precision.h; row++) {
  33684. for (col = 0; col < precision.w; col++) {
  33685. var square = [
  33686. base + col + row * rowLength,
  33687. base + (col + 1) + row * rowLength,
  33688. base + (col + 1) + (row + 1) * rowLength,
  33689. base + col + (row + 1) * rowLength
  33690. ];
  33691. indices.push(square[1]);
  33692. indices.push(square[2]);
  33693. indices.push(square[3]);
  33694. indices.push(square[0]);
  33695. indices.push(square[1]);
  33696. indices.push(square[3]);
  33697. }
  33698. }
  33699. // Position, normals and uvs
  33700. var position = BABYLON.Vector3.Zero();
  33701. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33702. for (row = 0; row <= precision.h; row++) {
  33703. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33704. for (col = 0; col <= precision.w; col++) {
  33705. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33706. position.y = 0;
  33707. positions.push(position.x, position.y, position.z);
  33708. normals.push(normal.x, normal.y, normal.z);
  33709. uvs.push(col / precision.w, row / precision.h);
  33710. }
  33711. }
  33712. }
  33713. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33714. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33715. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33716. }
  33717. }
  33718. // Result
  33719. var vertexData = new VertexData();
  33720. vertexData.indices = indices;
  33721. vertexData.positions = positions;
  33722. vertexData.normals = normals;
  33723. vertexData.uvs = uvs;
  33724. return vertexData;
  33725. };
  33726. /**
  33727. * Creates the VertexData of the Ground designed from a heightmap.
  33728. */
  33729. VertexData.CreateGroundFromHeightMap = function (options) {
  33730. var indices = [];
  33731. var positions = [];
  33732. var normals = [];
  33733. var uvs = [];
  33734. var row, col;
  33735. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33736. // Vertices
  33737. for (row = 0; row <= options.subdivisions; row++) {
  33738. for (col = 0; col <= options.subdivisions; col++) {
  33739. 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));
  33740. // Compute height
  33741. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33742. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33743. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33744. var r = options.buffer[pos] / 255.0;
  33745. var g = options.buffer[pos + 1] / 255.0;
  33746. var b = options.buffer[pos + 2] / 255.0;
  33747. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33748. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33749. // Add vertex
  33750. positions.push(position.x, position.y, position.z);
  33751. normals.push(0, 0, 0);
  33752. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33753. }
  33754. }
  33755. // Indices
  33756. for (row = 0; row < options.subdivisions; row++) {
  33757. for (col = 0; col < options.subdivisions; col++) {
  33758. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33759. indices.push(col + 1 + row * (options.subdivisions + 1));
  33760. indices.push(col + row * (options.subdivisions + 1));
  33761. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33762. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33763. indices.push(col + row * (options.subdivisions + 1));
  33764. }
  33765. }
  33766. // Normals
  33767. VertexData.ComputeNormals(positions, indices, normals);
  33768. // Result
  33769. var vertexData = new VertexData();
  33770. vertexData.indices = indices;
  33771. vertexData.positions = positions;
  33772. vertexData.normals = normals;
  33773. vertexData.uvs = uvs;
  33774. return vertexData;
  33775. };
  33776. /**
  33777. * Creates the VertexData of the Plane.
  33778. */
  33779. VertexData.CreatePlane = function (options) {
  33780. var indices = [];
  33781. var positions = [];
  33782. var normals = [];
  33783. var uvs = [];
  33784. var width = options.width || options.size || 1;
  33785. var height = options.height || options.size || 1;
  33786. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33787. // Vertices
  33788. var halfWidth = width / 2.0;
  33789. var halfHeight = height / 2.0;
  33790. positions.push(-halfWidth, -halfHeight, 0);
  33791. normals.push(0, 0, -1.0);
  33792. uvs.push(0.0, 0.0);
  33793. positions.push(halfWidth, -halfHeight, 0);
  33794. normals.push(0, 0, -1.0);
  33795. uvs.push(1.0, 0.0);
  33796. positions.push(halfWidth, halfHeight, 0);
  33797. normals.push(0, 0, -1.0);
  33798. uvs.push(1.0, 1.0);
  33799. positions.push(-halfWidth, halfHeight, 0);
  33800. normals.push(0, 0, -1.0);
  33801. uvs.push(0.0, 1.0);
  33802. // Indices
  33803. indices.push(0);
  33804. indices.push(1);
  33805. indices.push(2);
  33806. indices.push(0);
  33807. indices.push(2);
  33808. indices.push(3);
  33809. // Sides
  33810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33811. // Result
  33812. var vertexData = new VertexData();
  33813. vertexData.indices = indices;
  33814. vertexData.positions = positions;
  33815. vertexData.normals = normals;
  33816. vertexData.uvs = uvs;
  33817. return vertexData;
  33818. };
  33819. /**
  33820. * Creates the VertexData of the Disc or regular Polygon.
  33821. */
  33822. VertexData.CreateDisc = function (options) {
  33823. var positions = new Array();
  33824. var indices = new Array();
  33825. var normals = new Array();
  33826. var uvs = new Array();
  33827. var radius = options.radius || 0.5;
  33828. var tessellation = options.tessellation || 64;
  33829. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33830. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33831. // positions and uvs
  33832. positions.push(0, 0, 0); // disc center first
  33833. uvs.push(0.5, 0.5);
  33834. var theta = Math.PI * 2 * arc;
  33835. var step = theta / tessellation;
  33836. for (var a = 0; a < theta; a += step) {
  33837. var x = Math.cos(a);
  33838. var y = Math.sin(a);
  33839. var u = (x + 1) / 2;
  33840. var v = (1 - y) / 2;
  33841. positions.push(radius * x, radius * y, 0);
  33842. uvs.push(u, v);
  33843. }
  33844. if (arc === 1) {
  33845. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33846. uvs.push(uvs[2], uvs[3]);
  33847. }
  33848. //indices
  33849. var vertexNb = positions.length / 3;
  33850. for (var i = 1; i < vertexNb - 1; i++) {
  33851. indices.push(i + 1, 0, i);
  33852. }
  33853. // result
  33854. VertexData.ComputeNormals(positions, indices, normals);
  33855. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33856. var vertexData = new VertexData();
  33857. vertexData.indices = indices;
  33858. vertexData.positions = positions;
  33859. vertexData.normals = normals;
  33860. vertexData.uvs = uvs;
  33861. return vertexData;
  33862. };
  33863. /**
  33864. * Re-creates the VertexData of the Polygon for sideOrientation.
  33865. */
  33866. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33867. var faceUV = fUV || new Array(3);
  33868. var faceColors = fColors;
  33869. var colors = [];
  33870. // default face colors and UV if undefined
  33871. for (var f = 0; f < 3; f++) {
  33872. if (faceUV[f] === undefined) {
  33873. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33874. }
  33875. if (faceColors && faceColors[f] === undefined) {
  33876. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33877. }
  33878. }
  33879. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33880. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33881. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33882. var indices = polygon.getIndices();
  33883. // set face colours and textures
  33884. var idx = 0;
  33885. var face = 0;
  33886. for (var index = 0; index < normals.length; index += 3) {
  33887. //Edge Face no. 1
  33888. if (Math.abs(normals[index + 1]) < 0.001) {
  33889. face = 1;
  33890. }
  33891. //Top Face no. 0
  33892. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33893. face = 0;
  33894. }
  33895. //Bottom Face no. 2
  33896. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33897. face = 2;
  33898. }
  33899. idx = index / 3;
  33900. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33901. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33902. if (faceColors) {
  33903. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33904. }
  33905. }
  33906. // sides
  33907. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33908. // Result
  33909. var vertexData = new VertexData();
  33910. vertexData.indices = indices;
  33911. vertexData.positions = positions;
  33912. vertexData.normals = normals;
  33913. vertexData.uvs = uvs;
  33914. if (faceColors) {
  33915. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33916. vertexData.colors = totalColors;
  33917. }
  33918. return vertexData;
  33919. };
  33920. /**
  33921. * Creates the VertexData of the IcoSphere.
  33922. */
  33923. VertexData.CreateIcoSphere = function (options) {
  33924. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33925. var radius = options.radius || 1;
  33926. var flat = (options.flat === undefined) ? true : options.flat;
  33927. var subdivisions = options.subdivisions || 4;
  33928. var radiusX = options.radiusX || radius;
  33929. var radiusY = options.radiusY || radius;
  33930. var radiusZ = options.radiusZ || radius;
  33931. var t = (1 + Math.sqrt(5)) / 2;
  33932. // 12 vertex x,y,z
  33933. var ico_vertices = [
  33934. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33935. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33936. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33937. ];
  33938. // index of 3 vertex makes a face of icopshere
  33939. var ico_indices = [
  33940. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33941. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33942. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33943. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33944. ];
  33945. // vertex for uv have aliased position, not for UV
  33946. var vertices_unalias_id = [
  33947. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33948. // vertex alias
  33949. 0,
  33950. 2,
  33951. 3,
  33952. 3,
  33953. 3,
  33954. 4,
  33955. 7,
  33956. 8,
  33957. 9,
  33958. 9,
  33959. 10,
  33960. 11 // 23: B + 12
  33961. ];
  33962. // uv as integer step (not pixels !)
  33963. var ico_vertexuv = [
  33964. 5, 1, 3, 1, 6, 4, 0, 0,
  33965. 5, 3, 4, 2, 2, 2, 4, 0,
  33966. 2, 0, 1, 1, 6, 0, 6, 2,
  33967. // vertex alias (for same vertex on different faces)
  33968. 0, 4,
  33969. 3, 3,
  33970. 4, 4,
  33971. 3, 1,
  33972. 4, 2,
  33973. 4, 4,
  33974. 0, 2,
  33975. 1, 1,
  33976. 2, 2,
  33977. 3, 3,
  33978. 1, 3,
  33979. 2, 4 // 23: B + 12
  33980. ];
  33981. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33982. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33983. // First island of uv mapping
  33984. // v = 4h 3+ 2
  33985. // v = 3h 9+ 4
  33986. // v = 2h 9+ 5 B
  33987. // v = 1h 9 1 0
  33988. // v = 0h 3 8 7 A
  33989. // u = 0 1 2 3 4 5 6 *a
  33990. // Second island of uv mapping
  33991. // v = 4h 0+ B+ 4+
  33992. // v = 3h A+ 2+
  33993. // v = 2h 7+ 6 3+
  33994. // v = 1h 8+ 3+
  33995. // v = 0h
  33996. // u = 0 1 2 3 4 5 6 *a
  33997. // Face layout on texture UV mapping
  33998. // ============
  33999. // \ 4 /\ 16 / ======
  34000. // \ / \ / /\ 11 /
  34001. // \/ 7 \/ / \ /
  34002. // ======= / 10 \/
  34003. // /\ 17 /\ =======
  34004. // / \ / \ \ 15 /\
  34005. // / 8 \/ 12 \ \ / \
  34006. // ============ \/ 6 \
  34007. // \ 18 /\ ============
  34008. // \ / \ \ 5 /\ 0 /
  34009. // \/ 13 \ \ / \ /
  34010. // ======= \/ 1 \/
  34011. // =============
  34012. // /\ 19 /\ 2 /\
  34013. // / \ / \ / \
  34014. // / 14 \/ 9 \/ 3 \
  34015. // ===================
  34016. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34017. var ustep = 138 / 1024;
  34018. var vstep = 239 / 1024;
  34019. var uoffset = 60 / 1024;
  34020. var voffset = 26 / 1024;
  34021. // Second island should have margin, not to touch the first island
  34022. // avoid any borderline artefact in pixel rounding
  34023. var island_u_offset = -40 / 1024;
  34024. var island_v_offset = +20 / 1024;
  34025. // face is either island 0 or 1 :
  34026. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34027. var island = [
  34028. 0, 0, 0, 0, 1,
  34029. 0, 0, 1, 1, 0,
  34030. 0, 0, 1, 1, 0,
  34031. 0, 1, 1, 1, 0 // 15 - 19
  34032. ];
  34033. var indices = new Array();
  34034. var positions = new Array();
  34035. var normals = new Array();
  34036. var uvs = new Array();
  34037. var current_indice = 0;
  34038. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34039. var face_vertex_pos = new Array(3);
  34040. var face_vertex_uv = new Array(3);
  34041. var v012;
  34042. for (v012 = 0; v012 < 3; v012++) {
  34043. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34044. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34045. }
  34046. // create all with normals
  34047. for (var face = 0; face < 20; face++) {
  34048. // 3 vertex per face
  34049. for (v012 = 0; v012 < 3; v012++) {
  34050. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34051. var v_id = ico_indices[3 * face + v012];
  34052. // vertex have 3D position (x,y,z)
  34053. 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]);
  34054. // Normalize to get normal, then scale to radius
  34055. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34056. // uv Coordinates from vertex ID
  34057. 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);
  34058. }
  34059. // Subdivide the face (interpolate pos, norm, uv)
  34060. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34061. // - norm is linear interpolation of vertex corner normal
  34062. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34063. // - uv is linear interpolation
  34064. //
  34065. // Topology is as below for sub-divide by 2
  34066. // vertex shown as v0,v1,v2
  34067. // interp index is i1 to progress in range [v0,v1[
  34068. // interp index is i2 to progress in range [v0,v2[
  34069. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34070. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34071. //
  34072. //
  34073. // i2 v2
  34074. // ^ ^
  34075. // / / \
  34076. // / / \
  34077. // / / \
  34078. // / / (0,1) \
  34079. // / #---------\
  34080. // / / \ (0,0)'/ \
  34081. // / / \ / \
  34082. // / / \ / \
  34083. // / / (0,0) \ / (1,0) \
  34084. // / #---------#---------\
  34085. // v0 v1
  34086. //
  34087. // --------------------> i1
  34088. //
  34089. // interp of (i1,i2):
  34090. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34091. // along i1 : lerp(x0,x1, i1/(S-i2))
  34092. //
  34093. // centroid of triangle is needed to get help normal computation
  34094. // (c1,c2) are used for centroid location
  34095. var interp_vertex = function (i1, i2, c1, c2) {
  34096. // vertex is interpolated from
  34097. // - face_vertex_pos[0..2]
  34098. // - face_vertex_uv[0..2]
  34099. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34100. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34101. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34102. pos_interp.normalize();
  34103. var vertex_normal;
  34104. if (flat) {
  34105. // in flat mode, recalculate normal as face centroid normal
  34106. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34107. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34108. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34109. }
  34110. else {
  34111. // in smooth mode, recalculate normal from each single vertex position
  34112. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34113. }
  34114. // Vertex normal need correction due to X,Y,Z radius scaling
  34115. vertex_normal.x /= radiusX;
  34116. vertex_normal.y /= radiusY;
  34117. vertex_normal.z /= radiusZ;
  34118. vertex_normal.normalize();
  34119. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34120. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34121. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34122. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34123. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34124. uvs.push(uv_interp.x, uv_interp.y);
  34125. // push each vertex has member of a face
  34126. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34127. indices.push(current_indice);
  34128. current_indice++;
  34129. };
  34130. for (var i2 = 0; i2 < subdivisions; i2++) {
  34131. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34132. // face : (i1,i2) for /\ :
  34133. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34134. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34135. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34136. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34137. if (i1 + i2 + 1 < subdivisions) {
  34138. // face : (i1,i2)' for \/ :
  34139. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34140. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34141. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34142. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34143. }
  34144. }
  34145. }
  34146. }
  34147. // Sides
  34148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34149. // Result
  34150. var vertexData = new VertexData();
  34151. vertexData.indices = indices;
  34152. vertexData.positions = positions;
  34153. vertexData.normals = normals;
  34154. vertexData.uvs = uvs;
  34155. return vertexData;
  34156. };
  34157. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34158. /**
  34159. * Creates the VertexData of the Polyhedron.
  34160. */
  34161. VertexData.CreatePolyhedron = function (options) {
  34162. // provided polyhedron types :
  34163. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34164. // 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)
  34165. var polyhedra = [];
  34166. 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]] };
  34167. 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]] };
  34168. polyhedra[2] = {
  34169. 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]],
  34170. 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]]
  34171. };
  34172. polyhedra[3] = {
  34173. 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]],
  34174. 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]]
  34175. };
  34176. polyhedra[4] = {
  34177. 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]],
  34178. 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]]
  34179. };
  34180. 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]] };
  34181. 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]] };
  34182. 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]] };
  34183. 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]] };
  34184. 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]] };
  34185. 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]] };
  34186. 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]] };
  34187. 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]] };
  34188. 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]] };
  34189. polyhedra[14] = {
  34190. 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]],
  34191. 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]]
  34192. };
  34193. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34194. var size = options.size;
  34195. var sizeX = options.sizeX || size || 1;
  34196. var sizeY = options.sizeY || size || 1;
  34197. var sizeZ = options.sizeZ || size || 1;
  34198. var data = options.custom || polyhedra[type];
  34199. var nbfaces = data.face.length;
  34200. var faceUV = options.faceUV || new Array(nbfaces);
  34201. var faceColors = options.faceColors;
  34202. var flat = (options.flat === undefined) ? true : options.flat;
  34203. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34204. var positions = new Array();
  34205. var indices = new Array();
  34206. var normals = new Array();
  34207. var uvs = new Array();
  34208. var colors = new Array();
  34209. var index = 0;
  34210. var faceIdx = 0; // face cursor in the array "indexes"
  34211. var indexes = new Array();
  34212. var i = 0;
  34213. var f = 0;
  34214. var u, v, ang, x, y, tmp;
  34215. // default face colors and UV if undefined
  34216. if (flat) {
  34217. for (f = 0; f < nbfaces; f++) {
  34218. if (faceColors && faceColors[f] === undefined) {
  34219. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34220. }
  34221. if (faceUV && faceUV[f] === undefined) {
  34222. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34223. }
  34224. }
  34225. }
  34226. if (!flat) {
  34227. for (i = 0; i < data.vertex.length; i++) {
  34228. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34229. uvs.push(0, 0);
  34230. }
  34231. for (f = 0; f < nbfaces; f++) {
  34232. for (i = 0; i < data.face[f].length - 2; i++) {
  34233. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34234. }
  34235. }
  34236. }
  34237. else {
  34238. for (f = 0; f < nbfaces; f++) {
  34239. var fl = data.face[f].length; // number of vertices of the current face
  34240. ang = 2 * Math.PI / fl;
  34241. x = 0.5 * Math.tan(ang / 2);
  34242. y = 0.5;
  34243. // positions, uvs, colors
  34244. for (i = 0; i < fl; i++) {
  34245. // positions
  34246. 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);
  34247. indexes.push(index);
  34248. index++;
  34249. // uvs
  34250. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34251. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34252. uvs.push(u, v);
  34253. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34254. y = x * Math.sin(ang) + y * Math.cos(ang);
  34255. x = tmp;
  34256. // colors
  34257. if (faceColors) {
  34258. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34259. }
  34260. }
  34261. // indices from indexes
  34262. for (i = 0; i < fl - 2; i++) {
  34263. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34264. }
  34265. faceIdx += fl;
  34266. }
  34267. }
  34268. VertexData.ComputeNormals(positions, indices, normals);
  34269. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34270. var vertexData = new VertexData();
  34271. vertexData.positions = positions;
  34272. vertexData.indices = indices;
  34273. vertexData.normals = normals;
  34274. vertexData.uvs = uvs;
  34275. if (faceColors && flat) {
  34276. vertexData.colors = colors;
  34277. }
  34278. return vertexData;
  34279. };
  34280. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34281. /**
  34282. * Creates the VertexData of the Torus Knot.
  34283. */
  34284. VertexData.CreateTorusKnot = function (options) {
  34285. var indices = new Array();
  34286. var positions = new Array();
  34287. var normals = new Array();
  34288. var uvs = new Array();
  34289. var radius = options.radius || 2;
  34290. var tube = options.tube || 0.5;
  34291. var radialSegments = options.radialSegments || 32;
  34292. var tubularSegments = options.tubularSegments || 32;
  34293. var p = options.p || 2;
  34294. var q = options.q || 3;
  34295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34296. // Helper
  34297. var getPos = function (angle) {
  34298. var cu = Math.cos(angle);
  34299. var su = Math.sin(angle);
  34300. var quOverP = q / p * angle;
  34301. var cs = Math.cos(quOverP);
  34302. var tx = radius * (2 + cs) * 0.5 * cu;
  34303. var ty = radius * (2 + cs) * su * 0.5;
  34304. var tz = radius * Math.sin(quOverP) * 0.5;
  34305. return new BABYLON.Vector3(tx, ty, tz);
  34306. };
  34307. // Vertices
  34308. var i;
  34309. var j;
  34310. for (i = 0; i <= radialSegments; i++) {
  34311. var modI = i % radialSegments;
  34312. var u = modI / radialSegments * 2 * p * Math.PI;
  34313. var p1 = getPos(u);
  34314. var p2 = getPos(u + 0.01);
  34315. var tang = p2.subtract(p1);
  34316. var n = p2.add(p1);
  34317. var bitan = BABYLON.Vector3.Cross(tang, n);
  34318. n = BABYLON.Vector3.Cross(bitan, tang);
  34319. bitan.normalize();
  34320. n.normalize();
  34321. for (j = 0; j < tubularSegments; j++) {
  34322. var modJ = j % tubularSegments;
  34323. var v = modJ / tubularSegments * 2 * Math.PI;
  34324. var cx = -tube * Math.cos(v);
  34325. var cy = tube * Math.sin(v);
  34326. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34327. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34328. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34329. uvs.push(i / radialSegments);
  34330. uvs.push(j / tubularSegments);
  34331. }
  34332. }
  34333. for (i = 0; i < radialSegments; i++) {
  34334. for (j = 0; j < tubularSegments; j++) {
  34335. var jNext = (j + 1) % tubularSegments;
  34336. var a = i * tubularSegments + j;
  34337. var b = (i + 1) * tubularSegments + j;
  34338. var c = (i + 1) * tubularSegments + jNext;
  34339. var d = i * tubularSegments + jNext;
  34340. indices.push(d);
  34341. indices.push(b);
  34342. indices.push(a);
  34343. indices.push(d);
  34344. indices.push(c);
  34345. indices.push(b);
  34346. }
  34347. }
  34348. // Normals
  34349. VertexData.ComputeNormals(positions, indices, normals);
  34350. // Sides
  34351. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34352. // Result
  34353. var vertexData = new VertexData();
  34354. vertexData.indices = indices;
  34355. vertexData.positions = positions;
  34356. vertexData.normals = normals;
  34357. vertexData.uvs = uvs;
  34358. return vertexData;
  34359. };
  34360. // Tools
  34361. /**
  34362. * @param {any} - positions (number[] or Float32Array)
  34363. * @param {any} - indices (number[] or Uint16Array)
  34364. * @param {any} - normals (number[] or Float32Array)
  34365. * options (optional) :
  34366. * facetPositions : optional array of facet positions (vector3)
  34367. * facetNormals : optional array of facet normals (vector3)
  34368. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34369. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34370. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34371. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34372. * bInfo : optional bounding info, required for facetPartitioning computation
  34373. * useRightHandedSystem: optional boolean to for right handed system computation
  34374. * depthSort : optional boolean to enable the facet depth sort computation
  34375. * distanceTo : optional Vector3 to compute the facet depth from this location
  34376. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34377. */
  34378. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34379. // temporary scalar variables
  34380. var index = 0; // facet index
  34381. var p1p2x = 0.0; // p1p2 vector x coordinate
  34382. var p1p2y = 0.0; // p1p2 vector y coordinate
  34383. var p1p2z = 0.0; // p1p2 vector z coordinate
  34384. var p3p2x = 0.0; // p3p2 vector x coordinate
  34385. var p3p2y = 0.0; // p3p2 vector y coordinate
  34386. var p3p2z = 0.0; // p3p2 vector z coordinate
  34387. var faceNormalx = 0.0; // facet normal x coordinate
  34388. var faceNormaly = 0.0; // facet normal y coordinate
  34389. var faceNormalz = 0.0; // facet normal z coordinate
  34390. var length = 0.0; // facet normal length before normalization
  34391. var v1x = 0; // vector1 x index in the positions array
  34392. var v1y = 0; // vector1 y index in the positions array
  34393. var v1z = 0; // vector1 z index in the positions array
  34394. var v2x = 0; // vector2 x index in the positions array
  34395. var v2y = 0; // vector2 y index in the positions array
  34396. var v2z = 0; // vector2 z index in the positions array
  34397. var v3x = 0; // vector3 x index in the positions array
  34398. var v3y = 0; // vector3 y index in the positions array
  34399. var v3z = 0; // vector3 z index in the positions array
  34400. var computeFacetNormals = false;
  34401. var computeFacetPositions = false;
  34402. var computeFacetPartitioning = false;
  34403. var computeDepthSort = false;
  34404. var faceNormalSign = 1;
  34405. var ratio = 0;
  34406. var distanceTo = null;
  34407. if (options) {
  34408. computeFacetNormals = (options.facetNormals) ? true : false;
  34409. computeFacetPositions = (options.facetPositions) ? true : false;
  34410. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34411. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34412. ratio = options.ratio || 0;
  34413. computeDepthSort = (options.depthSort) ? true : false;
  34414. distanceTo = (options.distanceTo);
  34415. if (computeDepthSort) {
  34416. if (distanceTo === undefined) {
  34417. distanceTo = BABYLON.Vector3.Zero();
  34418. }
  34419. var depthSortedFacets = options.depthSortedFacets;
  34420. }
  34421. }
  34422. // facetPartitioning reinit if needed
  34423. var xSubRatio = 0;
  34424. var ySubRatio = 0;
  34425. var zSubRatio = 0;
  34426. var subSq = 0;
  34427. if (computeFacetPartitioning && options && options.bbSize) {
  34428. var ox = 0; // X partitioning index for facet position
  34429. var oy = 0; // Y partinioning index for facet position
  34430. var oz = 0; // Z partinioning index for facet position
  34431. var b1x = 0; // X partitioning index for facet v1 vertex
  34432. var b1y = 0; // Y partitioning index for facet v1 vertex
  34433. var b1z = 0; // z partitioning index for facet v1 vertex
  34434. var b2x = 0; // X partitioning index for facet v2 vertex
  34435. var b2y = 0; // Y partitioning index for facet v2 vertex
  34436. var b2z = 0; // Z partitioning index for facet v2 vertex
  34437. var b3x = 0; // X partitioning index for facet v3 vertex
  34438. var b3y = 0; // Y partitioning index for facet v3 vertex
  34439. var b3z = 0; // Z partitioning index for facet v3 vertex
  34440. var block_idx_o = 0; // facet barycenter block index
  34441. var block_idx_v1 = 0; // v1 vertex block index
  34442. var block_idx_v2 = 0; // v2 vertex block index
  34443. var block_idx_v3 = 0; // v3 vertex block index
  34444. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34445. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34446. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34447. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34448. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34449. subSq = options.subDiv.max * options.subDiv.max;
  34450. options.facetPartitioning.length = 0;
  34451. }
  34452. // reset the normals
  34453. for (index = 0; index < positions.length; index++) {
  34454. normals[index] = 0.0;
  34455. }
  34456. // Loop : 1 indice triplet = 1 facet
  34457. var nbFaces = (indices.length / 3) | 0;
  34458. for (index = 0; index < nbFaces; index++) {
  34459. // get the indexes of the coordinates of each vertex of the facet
  34460. v1x = indices[index * 3] * 3;
  34461. v1y = v1x + 1;
  34462. v1z = v1x + 2;
  34463. v2x = indices[index * 3 + 1] * 3;
  34464. v2y = v2x + 1;
  34465. v2z = v2x + 2;
  34466. v3x = indices[index * 3 + 2] * 3;
  34467. v3y = v3x + 1;
  34468. v3z = v3x + 2;
  34469. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34470. p1p2y = positions[v1y] - positions[v2y];
  34471. p1p2z = positions[v1z] - positions[v2z];
  34472. p3p2x = positions[v3x] - positions[v2x];
  34473. p3p2y = positions[v3y] - positions[v2y];
  34474. p3p2z = positions[v3z] - positions[v2z];
  34475. // compute the face normal with the cross product
  34476. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34477. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34478. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34479. // normalize this normal and store it in the array facetData
  34480. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34481. length = (length === 0) ? 1.0 : length;
  34482. faceNormalx /= length;
  34483. faceNormaly /= length;
  34484. faceNormalz /= length;
  34485. if (computeFacetNormals && options) {
  34486. options.facetNormals[index].x = faceNormalx;
  34487. options.facetNormals[index].y = faceNormaly;
  34488. options.facetNormals[index].z = faceNormalz;
  34489. }
  34490. if (computeFacetPositions && options) {
  34491. // compute and the facet barycenter coordinates in the array facetPositions
  34492. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34493. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34494. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34495. }
  34496. if (computeFacetPartitioning && options) {
  34497. // store the facet indexes in arrays in the main facetPartitioning array :
  34498. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34499. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34500. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34501. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34502. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34503. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34504. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34505. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34506. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34507. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34508. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34509. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34510. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34511. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34512. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34513. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34514. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34515. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34516. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34517. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34518. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34519. // push each facet index in each block containing the vertex
  34520. options.facetPartitioning[block_idx_v1].push(index);
  34521. if (block_idx_v2 != block_idx_v1) {
  34522. options.facetPartitioning[block_idx_v2].push(index);
  34523. }
  34524. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34525. options.facetPartitioning[block_idx_v3].push(index);
  34526. }
  34527. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34528. options.facetPartitioning[block_idx_o].push(index);
  34529. }
  34530. }
  34531. if (computeDepthSort && options && options.facetPositions) {
  34532. var dsf = depthSortedFacets[index];
  34533. dsf.ind = index * 3;
  34534. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34535. }
  34536. // compute the normals anyway
  34537. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34538. normals[v1y] += faceNormaly;
  34539. normals[v1z] += faceNormalz;
  34540. normals[v2x] += faceNormalx;
  34541. normals[v2y] += faceNormaly;
  34542. normals[v2z] += faceNormalz;
  34543. normals[v3x] += faceNormalx;
  34544. normals[v3y] += faceNormaly;
  34545. normals[v3z] += faceNormalz;
  34546. }
  34547. // last normalization of each normal
  34548. for (index = 0; index < normals.length / 3; index++) {
  34549. faceNormalx = normals[index * 3];
  34550. faceNormaly = normals[index * 3 + 1];
  34551. faceNormalz = normals[index * 3 + 2];
  34552. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34553. length = (length === 0) ? 1.0 : length;
  34554. faceNormalx /= length;
  34555. faceNormaly /= length;
  34556. faceNormalz /= length;
  34557. normals[index * 3] = faceNormalx;
  34558. normals[index * 3 + 1] = faceNormaly;
  34559. normals[index * 3 + 2] = faceNormalz;
  34560. }
  34561. };
  34562. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34563. var li = indices.length;
  34564. var ln = normals.length;
  34565. var i;
  34566. var n;
  34567. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34568. switch (sideOrientation) {
  34569. case BABYLON.Mesh.FRONTSIDE:
  34570. // nothing changed
  34571. break;
  34572. case BABYLON.Mesh.BACKSIDE:
  34573. var tmp;
  34574. // indices
  34575. for (i = 0; i < li; i += 3) {
  34576. tmp = indices[i];
  34577. indices[i] = indices[i + 2];
  34578. indices[i + 2] = tmp;
  34579. }
  34580. // normals
  34581. for (n = 0; n < ln; n++) {
  34582. normals[n] = -normals[n];
  34583. }
  34584. break;
  34585. case BABYLON.Mesh.DOUBLESIDE:
  34586. // positions
  34587. var lp = positions.length;
  34588. var l = lp / 3;
  34589. for (var p = 0; p < lp; p++) {
  34590. positions[lp + p] = positions[p];
  34591. }
  34592. // indices
  34593. for (i = 0; i < li; i += 3) {
  34594. indices[i + li] = indices[i + 2] + l;
  34595. indices[i + 1 + li] = indices[i + 1] + l;
  34596. indices[i + 2 + li] = indices[i] + l;
  34597. }
  34598. // normals
  34599. for (n = 0; n < ln; n++) {
  34600. normals[ln + n] = -normals[n];
  34601. }
  34602. // uvs
  34603. var lu = uvs.length;
  34604. var u = 0;
  34605. for (u = 0; u < lu; u++) {
  34606. uvs[u + lu] = uvs[u];
  34607. }
  34608. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34609. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34610. u = 0;
  34611. for (i = 0; i < lu / 2; i++) {
  34612. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34613. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34614. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34615. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34616. u += 2;
  34617. }
  34618. break;
  34619. }
  34620. };
  34621. /**
  34622. * Creates a new VertexData from the imported parameters.
  34623. */
  34624. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34625. var vertexData = new VertexData();
  34626. // positions
  34627. var positions = parsedVertexData.positions;
  34628. if (positions) {
  34629. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34630. }
  34631. // normals
  34632. var normals = parsedVertexData.normals;
  34633. if (normals) {
  34634. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34635. }
  34636. // tangents
  34637. var tangents = parsedVertexData.tangents;
  34638. if (tangents) {
  34639. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34640. }
  34641. // uvs
  34642. var uvs = parsedVertexData.uvs;
  34643. if (uvs) {
  34644. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34645. }
  34646. // uv2s
  34647. var uv2s = parsedVertexData.uv2s;
  34648. if (uv2s) {
  34649. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34650. }
  34651. // uv3s
  34652. var uv3s = parsedVertexData.uv3s;
  34653. if (uv3s) {
  34654. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34655. }
  34656. // uv4s
  34657. var uv4s = parsedVertexData.uv4s;
  34658. if (uv4s) {
  34659. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34660. }
  34661. // uv5s
  34662. var uv5s = parsedVertexData.uv5s;
  34663. if (uv5s) {
  34664. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34665. }
  34666. // uv6s
  34667. var uv6s = parsedVertexData.uv6s;
  34668. if (uv6s) {
  34669. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34670. }
  34671. // colors
  34672. var colors = parsedVertexData.colors;
  34673. if (colors) {
  34674. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34675. }
  34676. // matricesIndices
  34677. var matricesIndices = parsedVertexData.matricesIndices;
  34678. if (matricesIndices) {
  34679. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34680. }
  34681. // matricesWeights
  34682. var matricesWeights = parsedVertexData.matricesWeights;
  34683. if (matricesWeights) {
  34684. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34685. }
  34686. // indices
  34687. var indices = parsedVertexData.indices;
  34688. if (indices) {
  34689. vertexData.indices = indices;
  34690. }
  34691. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34692. };
  34693. return VertexData;
  34694. }());
  34695. BABYLON.VertexData = VertexData;
  34696. })(BABYLON || (BABYLON = {}));
  34697. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34698. var BABYLON;
  34699. (function (BABYLON) {
  34700. /**
  34701. * Class used to store geometry data (vertex buffers + index buffer)
  34702. */
  34703. var Geometry = /** @class */ (function () {
  34704. /**
  34705. * Creates a new geometry
  34706. * @param id defines the unique ID
  34707. * @param scene defines the hosting scene
  34708. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34709. * @param updatable defines if geometry must be updatable (false by default)
  34710. * @param mesh defines the mesh that will be associated with the geometry
  34711. */
  34712. function Geometry(id, scene, vertexData, updatable, mesh) {
  34713. if (updatable === void 0) { updatable = false; }
  34714. if (mesh === void 0) { mesh = null; }
  34715. /**
  34716. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34717. */
  34718. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34719. this._totalVertices = 0;
  34720. this._isDisposed = false;
  34721. this._indexBufferIsUpdatable = false;
  34722. this.id = id;
  34723. this._engine = scene.getEngine();
  34724. this._meshes = [];
  34725. this._scene = scene;
  34726. //Init vertex buffer cache
  34727. this._vertexBuffers = {};
  34728. this._indices = [];
  34729. this._updatable = updatable;
  34730. // vertexData
  34731. if (vertexData) {
  34732. this.setAllVerticesData(vertexData, updatable);
  34733. }
  34734. else {
  34735. this._totalVertices = 0;
  34736. this._indices = [];
  34737. }
  34738. if (this._engine.getCaps().vertexArrayObject) {
  34739. this._vertexArrayObjects = {};
  34740. }
  34741. // applyToMesh
  34742. if (mesh) {
  34743. if (mesh.getClassName() === "LinesMesh") {
  34744. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34745. this.updateExtend();
  34746. }
  34747. this.applyToMesh(mesh);
  34748. mesh.computeWorldMatrix(true);
  34749. }
  34750. }
  34751. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34752. /**
  34753. * 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
  34754. */
  34755. get: function () {
  34756. return this._boundingBias;
  34757. },
  34758. /**
  34759. * 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
  34760. */
  34761. set: function (value) {
  34762. if (this._boundingBias && this._boundingBias.equals(value)) {
  34763. return;
  34764. }
  34765. this._boundingBias = value.clone();
  34766. this.updateBoundingInfo(true, null);
  34767. },
  34768. enumerable: true,
  34769. configurable: true
  34770. });
  34771. /**
  34772. * Static function used to attach a new empty geometry to a mesh
  34773. * @param mesh defines the mesh to attach the geometry to
  34774. * @returns the new {BABYLON.Geometry}
  34775. */
  34776. Geometry.CreateGeometryForMesh = function (mesh) {
  34777. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34778. geometry.applyToMesh(mesh);
  34779. return geometry;
  34780. };
  34781. Object.defineProperty(Geometry.prototype, "extend", {
  34782. /**
  34783. * Gets the current extend of the geometry
  34784. */
  34785. get: function () {
  34786. return this._extend;
  34787. },
  34788. enumerable: true,
  34789. configurable: true
  34790. });
  34791. /**
  34792. * Gets the hosting scene
  34793. * @returns the hosting {BABYLON.Scene}
  34794. */
  34795. Geometry.prototype.getScene = function () {
  34796. return this._scene;
  34797. };
  34798. /**
  34799. * Gets the hosting engine
  34800. * @returns the hosting {BABYLON.Engine}
  34801. */
  34802. Geometry.prototype.getEngine = function () {
  34803. return this._engine;
  34804. };
  34805. /**
  34806. * Defines if the geometry is ready to use
  34807. * @returns true if the geometry is ready to be used
  34808. */
  34809. Geometry.prototype.isReady = function () {
  34810. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34811. };
  34812. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34813. /**
  34814. * Gets a value indicating that the geometry should not be serialized
  34815. */
  34816. get: function () {
  34817. for (var index = 0; index < this._meshes.length; index++) {
  34818. if (!this._meshes[index].doNotSerialize) {
  34819. return false;
  34820. }
  34821. }
  34822. return true;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. /** @ignore */
  34828. Geometry.prototype._rebuild = function () {
  34829. if (this._vertexArrayObjects) {
  34830. this._vertexArrayObjects = {};
  34831. }
  34832. // Index buffer
  34833. if (this._meshes.length !== 0 && this._indices) {
  34834. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34835. }
  34836. // Vertex buffers
  34837. for (var key in this._vertexBuffers) {
  34838. var vertexBuffer = this._vertexBuffers[key];
  34839. vertexBuffer._rebuild();
  34840. }
  34841. };
  34842. /**
  34843. * Affects all gemetry data in one call
  34844. * @param vertexData defines the geometry data
  34845. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34846. */
  34847. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34848. vertexData.applyToGeometry(this, updatable);
  34849. this.notifyUpdate();
  34850. };
  34851. /**
  34852. * Set specific vertex data
  34853. * @param kind defines the data kind (Position, normal, etc...)
  34854. * @param data defines the vertex data to use
  34855. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34856. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34857. */
  34858. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34859. if (updatable === void 0) { updatable = false; }
  34860. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34861. this.setVerticesBuffer(buffer);
  34862. };
  34863. /**
  34864. * Removes a specific vertex data
  34865. * @param kind defines the data kind (Position, normal, etc...)
  34866. */
  34867. Geometry.prototype.removeVerticesData = function (kind) {
  34868. if (this._vertexBuffers[kind]) {
  34869. this._vertexBuffers[kind].dispose();
  34870. delete this._vertexBuffers[kind];
  34871. }
  34872. };
  34873. /**
  34874. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34875. * @param buffer defines the vertex buffer to use
  34876. */
  34877. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34878. var kind = buffer.getKind();
  34879. if (this._vertexBuffers[kind]) {
  34880. this._vertexBuffers[kind].dispose();
  34881. }
  34882. this._vertexBuffers[kind] = buffer;
  34883. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34884. var data = buffer.getData();
  34885. var stride = buffer.getStrideSize();
  34886. this._totalVertices = data.length / stride;
  34887. this.updateExtend(data, stride);
  34888. this._resetPointsArrayCache();
  34889. var meshes = this._meshes;
  34890. var numOfMeshes = meshes.length;
  34891. for (var index = 0; index < numOfMeshes; index++) {
  34892. var mesh = meshes[index];
  34893. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34894. mesh._createGlobalSubMesh(false);
  34895. mesh.computeWorldMatrix(true);
  34896. }
  34897. }
  34898. this.notifyUpdate(kind);
  34899. if (this._vertexArrayObjects) {
  34900. this._disposeVertexArrayObjects();
  34901. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34902. }
  34903. };
  34904. /**
  34905. * Update a specific vertex buffer
  34906. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34907. * It will do nothing if the buffer is not updatable
  34908. * @param kind defines the data kind (Position, normal, etc...)
  34909. * @param data defines the data to use
  34910. * @param offset defines the offset in the target buffer where to store the data
  34911. */
  34912. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34913. var vertexBuffer = this.getVertexBuffer(kind);
  34914. if (!vertexBuffer) {
  34915. return;
  34916. }
  34917. vertexBuffer.updateDirectly(data, offset);
  34918. this.notifyUpdate(kind);
  34919. };
  34920. /**
  34921. * Update a specific vertex buffer
  34922. * This function will create a new buffer if the current one is not updatable
  34923. * @param kind defines the data kind (Position, normal, etc...)
  34924. * @param data defines the data to use
  34925. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34926. */
  34927. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34928. if (updateExtends === void 0) { updateExtends = false; }
  34929. var vertexBuffer = this.getVertexBuffer(kind);
  34930. if (!vertexBuffer) {
  34931. return;
  34932. }
  34933. vertexBuffer.update(data);
  34934. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34935. var stride = vertexBuffer.getStrideSize();
  34936. this._totalVertices = data.length / stride;
  34937. this.updateBoundingInfo(updateExtends, data);
  34938. }
  34939. this.notifyUpdate(kind);
  34940. };
  34941. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34942. if (updateExtends) {
  34943. this.updateExtend(data);
  34944. }
  34945. var meshes = this._meshes;
  34946. var numOfMeshes = meshes.length;
  34947. this._resetPointsArrayCache();
  34948. for (var index = 0; index < numOfMeshes; index++) {
  34949. var mesh = meshes[index];
  34950. if (updateExtends) {
  34951. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34952. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34953. var subMesh = mesh.subMeshes[subIndex];
  34954. subMesh.refreshBoundingInfo();
  34955. }
  34956. }
  34957. }
  34958. };
  34959. /** @ignore */
  34960. Geometry.prototype._bind = function (effect, indexToBind) {
  34961. if (!effect) {
  34962. return;
  34963. }
  34964. if (indexToBind === undefined) {
  34965. indexToBind = this._indexBuffer;
  34966. }
  34967. var vbs = this.getVertexBuffers();
  34968. if (!vbs) {
  34969. return;
  34970. }
  34971. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34972. this._engine.bindBuffers(vbs, indexToBind, effect);
  34973. return;
  34974. }
  34975. // Using VAO
  34976. if (!this._vertexArrayObjects[effect.key]) {
  34977. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34978. }
  34979. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34980. };
  34981. /**
  34982. * Gets total number of vertices
  34983. * @returns the total number of vertices
  34984. */
  34985. Geometry.prototype.getTotalVertices = function () {
  34986. if (!this.isReady()) {
  34987. return 0;
  34988. }
  34989. return this._totalVertices;
  34990. };
  34991. /**
  34992. * Gets a specific vertex data attached to this geometry
  34993. * @param kind defines the data kind (Position, normal, etc...)
  34994. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34995. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34996. * @returns a float array containing vertex data
  34997. */
  34998. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34999. var vertexBuffer = this.getVertexBuffer(kind);
  35000. if (!vertexBuffer) {
  35001. return null;
  35002. }
  35003. var orig = vertexBuffer.getData();
  35004. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35005. return orig;
  35006. }
  35007. else {
  35008. var len = orig.length;
  35009. var copy = [];
  35010. for (var i = 0; i < len; i++) {
  35011. copy.push(orig[i]);
  35012. }
  35013. return copy;
  35014. }
  35015. };
  35016. /**
  35017. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35018. * @param kind defines the data kind (Position, normal, etc...)
  35019. * @returns true if the vertex buffer with the specified kind is updatable
  35020. */
  35021. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35022. var vb = this._vertexBuffers[kind];
  35023. if (!vb) {
  35024. return false;
  35025. }
  35026. return vb.isUpdatable();
  35027. };
  35028. /**
  35029. * Gets a specific vertex buffer
  35030. * @param kind defines the data kind (Position, normal, etc...)
  35031. * @returns a {BABYLON.VertexBuffer}
  35032. */
  35033. Geometry.prototype.getVertexBuffer = function (kind) {
  35034. if (!this.isReady()) {
  35035. return null;
  35036. }
  35037. return this._vertexBuffers[kind];
  35038. };
  35039. /**
  35040. * Returns all vertex buffers
  35041. * @return an object holding all vertex buffers indexed by kind
  35042. */
  35043. Geometry.prototype.getVertexBuffers = function () {
  35044. if (!this.isReady()) {
  35045. return null;
  35046. }
  35047. return this._vertexBuffers;
  35048. };
  35049. /**
  35050. * Gets a boolean indicating if specific vertex buffer is present
  35051. * @param kind defines the data kind (Position, normal, etc...)
  35052. * @returns true if data is present
  35053. */
  35054. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35055. if (!this._vertexBuffers) {
  35056. if (this._delayInfo) {
  35057. return this._delayInfo.indexOf(kind) !== -1;
  35058. }
  35059. return false;
  35060. }
  35061. return this._vertexBuffers[kind] !== undefined;
  35062. };
  35063. /**
  35064. * Gets a list of all attached data kinds (Position, normal, etc...)
  35065. * @returns a list of string containing all kinds
  35066. */
  35067. Geometry.prototype.getVerticesDataKinds = function () {
  35068. var result = [];
  35069. var kind;
  35070. if (!this._vertexBuffers && this._delayInfo) {
  35071. for (kind in this._delayInfo) {
  35072. result.push(kind);
  35073. }
  35074. }
  35075. else {
  35076. for (kind in this._vertexBuffers) {
  35077. result.push(kind);
  35078. }
  35079. }
  35080. return result;
  35081. };
  35082. /**
  35083. * Update index buffer
  35084. * @param indices defines the indices to store in the index buffer
  35085. * @param offset defines the offset in the target buffer where to store the data
  35086. */
  35087. Geometry.prototype.updateIndices = function (indices, offset) {
  35088. if (!this._indexBuffer) {
  35089. return;
  35090. }
  35091. if (!this._indexBufferIsUpdatable) {
  35092. this.setIndices(indices, null, true);
  35093. }
  35094. else {
  35095. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35096. }
  35097. };
  35098. /**
  35099. * Creates a new index buffer
  35100. * @param indices defines the indices to store in the index buffer
  35101. * @param totalVertices defines the total number of vertices (could be null)
  35102. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35103. */
  35104. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35105. if (totalVertices === void 0) { totalVertices = null; }
  35106. if (updatable === void 0) { updatable = false; }
  35107. if (this._indexBuffer) {
  35108. this._engine._releaseBuffer(this._indexBuffer);
  35109. }
  35110. this._disposeVertexArrayObjects();
  35111. this._indices = indices;
  35112. this._indexBufferIsUpdatable = updatable;
  35113. if (this._meshes.length !== 0 && this._indices) {
  35114. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35115. }
  35116. if (totalVertices != undefined) {
  35117. this._totalVertices = totalVertices;
  35118. }
  35119. var meshes = this._meshes;
  35120. var numOfMeshes = meshes.length;
  35121. for (var index = 0; index < numOfMeshes; index++) {
  35122. meshes[index]._createGlobalSubMesh(true);
  35123. }
  35124. this.notifyUpdate();
  35125. };
  35126. /**
  35127. * Return the total number of indices
  35128. * @returns the total number of indices
  35129. */
  35130. Geometry.prototype.getTotalIndices = function () {
  35131. if (!this.isReady()) {
  35132. return 0;
  35133. }
  35134. return this._indices.length;
  35135. };
  35136. /**
  35137. * Gets the index buffer array
  35138. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35139. * @returns the index buffer array
  35140. */
  35141. Geometry.prototype.getIndices = function (copyWhenShared) {
  35142. if (!this.isReady()) {
  35143. return null;
  35144. }
  35145. var orig = this._indices;
  35146. if (!copyWhenShared || this._meshes.length === 1) {
  35147. return orig;
  35148. }
  35149. else {
  35150. var len = orig.length;
  35151. var copy = [];
  35152. for (var i = 0; i < len; i++) {
  35153. copy.push(orig[i]);
  35154. }
  35155. return copy;
  35156. }
  35157. };
  35158. /**
  35159. * Gets the index buffer
  35160. * @return the index buffer
  35161. */
  35162. Geometry.prototype.getIndexBuffer = function () {
  35163. if (!this.isReady()) {
  35164. return null;
  35165. }
  35166. return this._indexBuffer;
  35167. };
  35168. /** @ignore */
  35169. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35170. if (effect === void 0) { effect = null; }
  35171. if (!effect || !this._vertexArrayObjects) {
  35172. return;
  35173. }
  35174. if (this._vertexArrayObjects[effect.key]) {
  35175. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35176. delete this._vertexArrayObjects[effect.key];
  35177. }
  35178. };
  35179. /**
  35180. * Release the associated resources for a specific mesh
  35181. * @param mesh defines the source mesh
  35182. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35183. */
  35184. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35185. var meshes = this._meshes;
  35186. var index = meshes.indexOf(mesh);
  35187. if (index === -1) {
  35188. return;
  35189. }
  35190. meshes.splice(index, 1);
  35191. mesh._geometry = null;
  35192. if (meshes.length === 0 && shouldDispose) {
  35193. this.dispose();
  35194. }
  35195. };
  35196. /**
  35197. * Apply current geometry to a given mesh
  35198. * @param mesh defines the mesh to apply geometry to
  35199. */
  35200. Geometry.prototype.applyToMesh = function (mesh) {
  35201. if (mesh._geometry === this) {
  35202. return;
  35203. }
  35204. var previousGeometry = mesh._geometry;
  35205. if (previousGeometry) {
  35206. previousGeometry.releaseForMesh(mesh);
  35207. }
  35208. var meshes = this._meshes;
  35209. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35210. mesh._geometry = this;
  35211. this._scene.pushGeometry(this);
  35212. meshes.push(mesh);
  35213. if (this.isReady()) {
  35214. this._applyToMesh(mesh);
  35215. }
  35216. else {
  35217. mesh._boundingInfo = this._boundingInfo;
  35218. }
  35219. };
  35220. Geometry.prototype.updateExtend = function (data, stride) {
  35221. if (data === void 0) { data = null; }
  35222. if (!data) {
  35223. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35224. }
  35225. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35226. };
  35227. Geometry.prototype._applyToMesh = function (mesh) {
  35228. var numOfMeshes = this._meshes.length;
  35229. // vertexBuffers
  35230. for (var kind in this._vertexBuffers) {
  35231. if (numOfMeshes === 1) {
  35232. this._vertexBuffers[kind].create();
  35233. }
  35234. var buffer = this._vertexBuffers[kind].getBuffer();
  35235. if (buffer)
  35236. buffer.references = numOfMeshes;
  35237. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35238. if (!this._extend) {
  35239. this.updateExtend(this._vertexBuffers[kind].getData());
  35240. }
  35241. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35242. mesh._createGlobalSubMesh(false);
  35243. //bounding info was just created again, world matrix should be applied again.
  35244. mesh._updateBoundingInfo();
  35245. }
  35246. }
  35247. // indexBuffer
  35248. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35249. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35250. }
  35251. if (this._indexBuffer) {
  35252. this._indexBuffer.references = numOfMeshes;
  35253. }
  35254. };
  35255. Geometry.prototype.notifyUpdate = function (kind) {
  35256. if (this.onGeometryUpdated) {
  35257. this.onGeometryUpdated(this, kind);
  35258. }
  35259. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35260. var mesh = _a[_i];
  35261. mesh._markSubMeshesAsAttributesDirty();
  35262. }
  35263. };
  35264. /**
  35265. * Load the geometry if it was flagged as delay loaded
  35266. * @param scene defines the hosting scene
  35267. * @param onLoaded defines a callback called when the geometry is loaded
  35268. */
  35269. Geometry.prototype.load = function (scene, onLoaded) {
  35270. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35271. return;
  35272. }
  35273. if (this.isReady()) {
  35274. if (onLoaded) {
  35275. onLoaded();
  35276. }
  35277. return;
  35278. }
  35279. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35280. this._queueLoad(scene, onLoaded);
  35281. };
  35282. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35283. var _this = this;
  35284. if (!this.delayLoadingFile) {
  35285. return;
  35286. }
  35287. scene._addPendingData(this);
  35288. scene._loadFile(this.delayLoadingFile, function (data) {
  35289. if (!_this._delayLoadingFunction) {
  35290. return;
  35291. }
  35292. _this._delayLoadingFunction(JSON.parse(data), _this);
  35293. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35294. _this._delayInfo = [];
  35295. scene._removePendingData(_this);
  35296. var meshes = _this._meshes;
  35297. var numOfMeshes = meshes.length;
  35298. for (var index = 0; index < numOfMeshes; index++) {
  35299. _this._applyToMesh(meshes[index]);
  35300. }
  35301. if (onLoaded) {
  35302. onLoaded();
  35303. }
  35304. }, undefined, true);
  35305. };
  35306. /**
  35307. * Invert the geometry to move from a right handed system to a left handed one.
  35308. */
  35309. Geometry.prototype.toLeftHanded = function () {
  35310. // Flip faces
  35311. var tIndices = this.getIndices(false);
  35312. if (tIndices != null && tIndices.length > 0) {
  35313. for (var i = 0; i < tIndices.length; i += 3) {
  35314. var tTemp = tIndices[i + 0];
  35315. tIndices[i + 0] = tIndices[i + 2];
  35316. tIndices[i + 2] = tTemp;
  35317. }
  35318. this.setIndices(tIndices);
  35319. }
  35320. // Negate position.z
  35321. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35322. if (tPositions != null && tPositions.length > 0) {
  35323. for (var i = 0; i < tPositions.length; i += 3) {
  35324. tPositions[i + 2] = -tPositions[i + 2];
  35325. }
  35326. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35327. }
  35328. // Negate normal.z
  35329. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35330. if (tNormals != null && tNormals.length > 0) {
  35331. for (var i = 0; i < tNormals.length; i += 3) {
  35332. tNormals[i + 2] = -tNormals[i + 2];
  35333. }
  35334. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35335. }
  35336. };
  35337. // Cache
  35338. /** @ignore */
  35339. Geometry.prototype._resetPointsArrayCache = function () {
  35340. this._positions = null;
  35341. };
  35342. /** @ignore */
  35343. Geometry.prototype._generatePointsArray = function () {
  35344. if (this._positions)
  35345. return true;
  35346. this._positions = [];
  35347. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35348. if (!data) {
  35349. return false;
  35350. }
  35351. for (var index = 0; index < data.length; index += 3) {
  35352. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35353. }
  35354. return true;
  35355. };
  35356. /**
  35357. * Gets a value indicating if the geometry is disposed
  35358. * @returns true if the geometry was disposed
  35359. */
  35360. Geometry.prototype.isDisposed = function () {
  35361. return this._isDisposed;
  35362. };
  35363. Geometry.prototype._disposeVertexArrayObjects = function () {
  35364. if (this._vertexArrayObjects) {
  35365. for (var kind in this._vertexArrayObjects) {
  35366. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35367. }
  35368. this._vertexArrayObjects = {};
  35369. }
  35370. };
  35371. /**
  35372. * Free all associated resources
  35373. */
  35374. Geometry.prototype.dispose = function () {
  35375. var meshes = this._meshes;
  35376. var numOfMeshes = meshes.length;
  35377. var index;
  35378. for (index = 0; index < numOfMeshes; index++) {
  35379. this.releaseForMesh(meshes[index]);
  35380. }
  35381. this._meshes = [];
  35382. this._disposeVertexArrayObjects();
  35383. for (var kind in this._vertexBuffers) {
  35384. this._vertexBuffers[kind].dispose();
  35385. }
  35386. this._vertexBuffers = {};
  35387. this._totalVertices = 0;
  35388. if (this._indexBuffer) {
  35389. this._engine._releaseBuffer(this._indexBuffer);
  35390. }
  35391. this._indexBuffer = null;
  35392. this._indices = [];
  35393. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35394. this.delayLoadingFile = null;
  35395. this._delayLoadingFunction = null;
  35396. this._delayInfo = [];
  35397. this._boundingInfo = null;
  35398. this._scene.removeGeometry(this);
  35399. this._isDisposed = true;
  35400. };
  35401. /**
  35402. * Clone the current geometry into a new geometry
  35403. * @param id defines the unique ID of the new geometry
  35404. * @returns a new geometry object
  35405. */
  35406. Geometry.prototype.copy = function (id) {
  35407. var vertexData = new BABYLON.VertexData();
  35408. vertexData.indices = [];
  35409. var indices = this.getIndices();
  35410. if (indices) {
  35411. for (var index = 0; index < indices.length; index++) {
  35412. vertexData.indices.push(indices[index]);
  35413. }
  35414. }
  35415. var updatable = false;
  35416. var stopChecking = false;
  35417. var kind;
  35418. for (kind in this._vertexBuffers) {
  35419. // using slice() to make a copy of the array and not just reference it
  35420. var data = this.getVerticesData(kind);
  35421. if (data instanceof Float32Array) {
  35422. vertexData.set(new Float32Array(data), kind);
  35423. }
  35424. else {
  35425. vertexData.set(data.slice(0), kind);
  35426. }
  35427. if (!stopChecking) {
  35428. var vb = this.getVertexBuffer(kind);
  35429. if (vb) {
  35430. updatable = vb.isUpdatable();
  35431. stopChecking = !updatable;
  35432. }
  35433. }
  35434. }
  35435. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35436. geometry.delayLoadState = this.delayLoadState;
  35437. geometry.delayLoadingFile = this.delayLoadingFile;
  35438. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35439. for (kind in this._delayInfo) {
  35440. geometry._delayInfo = geometry._delayInfo || [];
  35441. geometry._delayInfo.push(kind);
  35442. }
  35443. // Bounding info
  35444. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35445. return geometry;
  35446. };
  35447. /**
  35448. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35449. * @return a JSON representation of the current geometry data (without the vertices data)
  35450. */
  35451. Geometry.prototype.serialize = function () {
  35452. var serializationObject = {};
  35453. serializationObject.id = this.id;
  35454. serializationObject.updatable = this._updatable;
  35455. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35456. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35457. }
  35458. return serializationObject;
  35459. };
  35460. Geometry.prototype.toNumberArray = function (origin) {
  35461. if (Array.isArray(origin)) {
  35462. return origin;
  35463. }
  35464. else {
  35465. return Array.prototype.slice.call(origin);
  35466. }
  35467. };
  35468. /**
  35469. * Serialize all vertices data into a JSON oject
  35470. * @returns a JSON representation of the current geometry data
  35471. */
  35472. Geometry.prototype.serializeVerticeData = function () {
  35473. var serializationObject = this.serialize();
  35474. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35475. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35476. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35477. serializationObject.positions._updatable = true;
  35478. }
  35479. }
  35480. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35481. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35482. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35483. serializationObject.normals._updatable = true;
  35484. }
  35485. }
  35486. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35487. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35488. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35489. serializationObject.tangets._updatable = true;
  35490. }
  35491. }
  35492. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35493. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35494. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35495. serializationObject.uvs._updatable = true;
  35496. }
  35497. }
  35498. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35499. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35500. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35501. serializationObject.uv2s._updatable = true;
  35502. }
  35503. }
  35504. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35505. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35506. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35507. serializationObject.uv3s._updatable = true;
  35508. }
  35509. }
  35510. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35511. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35512. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35513. serializationObject.uv4s._updatable = true;
  35514. }
  35515. }
  35516. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35517. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35518. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35519. serializationObject.uv5s._updatable = true;
  35520. }
  35521. }
  35522. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35523. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35524. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35525. serializationObject.uv6s._updatable = true;
  35526. }
  35527. }
  35528. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35529. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35530. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35531. serializationObject.colors._updatable = true;
  35532. }
  35533. }
  35534. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35535. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35536. serializationObject.matricesIndices._isExpanded = true;
  35537. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35538. serializationObject.matricesIndices._updatable = true;
  35539. }
  35540. }
  35541. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35542. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35543. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35544. serializationObject.matricesWeights._updatable = true;
  35545. }
  35546. }
  35547. serializationObject.indices = this.toNumberArray(this.getIndices());
  35548. return serializationObject;
  35549. };
  35550. // Statics
  35551. /**
  35552. * Extracts a clone of a mesh geometry
  35553. * @param mesh defines the source mesh
  35554. * @param id defines the unique ID of the new geometry object
  35555. * @returns the new geometry object
  35556. */
  35557. Geometry.ExtractFromMesh = function (mesh, id) {
  35558. var geometry = mesh._geometry;
  35559. if (!geometry) {
  35560. return null;
  35561. }
  35562. return geometry.copy(id);
  35563. };
  35564. /**
  35565. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35566. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35567. * Be aware Math.random() could cause collisions, but:
  35568. * "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"
  35569. * @returns a string containing a new GUID
  35570. */
  35571. Geometry.RandomId = function () {
  35572. return BABYLON.Tools.RandomId();
  35573. };
  35574. /** @ignore */
  35575. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35576. var scene = mesh.getScene();
  35577. // Geometry
  35578. var geometryId = parsedGeometry.geometryId;
  35579. if (geometryId) {
  35580. var geometry = scene.getGeometryByID(geometryId);
  35581. if (geometry) {
  35582. geometry.applyToMesh(mesh);
  35583. }
  35584. }
  35585. else if (parsedGeometry instanceof ArrayBuffer) {
  35586. var binaryInfo = mesh._binaryInfo;
  35587. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35588. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35589. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35590. }
  35591. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35592. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35593. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35594. }
  35595. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35596. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35597. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35598. }
  35599. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35600. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35601. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35602. }
  35603. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35604. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35605. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35606. }
  35607. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35608. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35609. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35610. }
  35611. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35612. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35613. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35614. }
  35615. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35616. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35617. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35618. }
  35619. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35620. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35621. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35622. }
  35623. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35624. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35625. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35626. }
  35627. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35628. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35630. }
  35631. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35632. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35634. }
  35635. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35636. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35637. mesh.setIndices(indicesData, null);
  35638. }
  35639. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35640. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35641. mesh.subMeshes = [];
  35642. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35643. var materialIndex = subMeshesData[(i * 5) + 0];
  35644. var verticesStart = subMeshesData[(i * 5) + 1];
  35645. var verticesCount = subMeshesData[(i * 5) + 2];
  35646. var indexStart = subMeshesData[(i * 5) + 3];
  35647. var indexCount = subMeshesData[(i * 5) + 4];
  35648. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35649. }
  35650. }
  35651. }
  35652. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35653. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35654. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35655. if (parsedGeometry.tangents) {
  35656. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35657. }
  35658. if (parsedGeometry.uvs) {
  35659. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35660. }
  35661. if (parsedGeometry.uvs2) {
  35662. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35663. }
  35664. if (parsedGeometry.uvs3) {
  35665. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35666. }
  35667. if (parsedGeometry.uvs4) {
  35668. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35669. }
  35670. if (parsedGeometry.uvs5) {
  35671. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35672. }
  35673. if (parsedGeometry.uvs6) {
  35674. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35675. }
  35676. if (parsedGeometry.colors) {
  35677. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35678. }
  35679. if (parsedGeometry.matricesIndices) {
  35680. if (!parsedGeometry.matricesIndices._isExpanded) {
  35681. var floatIndices = [];
  35682. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35683. var matricesIndex = parsedGeometry.matricesIndices[i];
  35684. floatIndices.push(matricesIndex & 0x000000FF);
  35685. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35686. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35687. floatIndices.push(matricesIndex >> 24);
  35688. }
  35689. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35690. }
  35691. else {
  35692. delete parsedGeometry.matricesIndices._isExpanded;
  35693. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35694. }
  35695. }
  35696. if (parsedGeometry.matricesIndicesExtra) {
  35697. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35698. var floatIndices = [];
  35699. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35700. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35701. floatIndices.push(matricesIndex & 0x000000FF);
  35702. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35703. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35704. floatIndices.push(matricesIndex >> 24);
  35705. }
  35706. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35707. }
  35708. else {
  35709. delete parsedGeometry.matricesIndices._isExpanded;
  35710. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35711. }
  35712. }
  35713. if (parsedGeometry.matricesWeights) {
  35714. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35715. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35716. }
  35717. if (parsedGeometry.matricesWeightsExtra) {
  35718. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35719. }
  35720. mesh.setIndices(parsedGeometry.indices, null);
  35721. }
  35722. // SubMeshes
  35723. if (parsedGeometry.subMeshes) {
  35724. mesh.subMeshes = [];
  35725. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35726. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35727. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35728. }
  35729. }
  35730. // Flat shading
  35731. if (mesh._shouldGenerateFlatShading) {
  35732. mesh.convertToFlatShadedMesh();
  35733. delete mesh._shouldGenerateFlatShading;
  35734. }
  35735. // Update
  35736. mesh.computeWorldMatrix(true);
  35737. // Octree
  35738. var sceneOctree = scene.selectionOctree;
  35739. if (sceneOctree !== undefined && sceneOctree !== null) {
  35740. sceneOctree.addMesh(mesh);
  35741. }
  35742. };
  35743. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35744. var epsilon = 1e-3;
  35745. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35746. return;
  35747. }
  35748. var noInfluenceBoneIndex = 0.0;
  35749. if (parsedGeometry.skeletonId > -1) {
  35750. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35751. if (!skeleton) {
  35752. return;
  35753. }
  35754. noInfluenceBoneIndex = skeleton.bones.length;
  35755. }
  35756. else {
  35757. return;
  35758. }
  35759. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35760. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35761. var matricesWeights = parsedGeometry.matricesWeights;
  35762. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35763. var influencers = parsedGeometry.numBoneInfluencer;
  35764. var size = matricesWeights.length;
  35765. for (var i = 0; i < size; i += 4) {
  35766. var weight = 0.0;
  35767. var firstZeroWeight = -1;
  35768. for (var j = 0; j < 4; j++) {
  35769. var w = matricesWeights[i + j];
  35770. weight += w;
  35771. if (w < epsilon && firstZeroWeight < 0) {
  35772. firstZeroWeight = j;
  35773. }
  35774. }
  35775. if (matricesWeightsExtra) {
  35776. for (var j = 0; j < 4; j++) {
  35777. var w = matricesWeightsExtra[i + j];
  35778. weight += w;
  35779. if (w < epsilon && firstZeroWeight < 0) {
  35780. firstZeroWeight = j + 4;
  35781. }
  35782. }
  35783. }
  35784. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35785. firstZeroWeight = influencers - 1;
  35786. }
  35787. if (weight > epsilon) {
  35788. var mweight = 1.0 / weight;
  35789. for (var j = 0; j < 4; j++) {
  35790. matricesWeights[i + j] *= mweight;
  35791. }
  35792. if (matricesWeightsExtra) {
  35793. for (var j = 0; j < 4; j++) {
  35794. matricesWeightsExtra[i + j] *= mweight;
  35795. }
  35796. }
  35797. }
  35798. else {
  35799. if (firstZeroWeight >= 4) {
  35800. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35801. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35802. }
  35803. else {
  35804. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35805. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35806. }
  35807. }
  35808. }
  35809. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35810. if (parsedGeometry.matricesWeightsExtra) {
  35811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35812. }
  35813. };
  35814. /**
  35815. * Create a new geometry from persisted data (Using .babylon file format)
  35816. * @param parsedVertexData defines the persisted data
  35817. * @param scene defines the hosting scene
  35818. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35819. * @returns the new geometry object
  35820. */
  35821. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35822. if (scene.getGeometryByID(parsedVertexData.id)) {
  35823. return null; // null since geometry could be something else than a box...
  35824. }
  35825. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35826. if (BABYLON.Tags) {
  35827. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35828. }
  35829. if (parsedVertexData.delayLoadingFile) {
  35830. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35831. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35832. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35833. geometry._delayInfo = [];
  35834. if (parsedVertexData.hasUVs) {
  35835. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35836. }
  35837. if (parsedVertexData.hasUVs2) {
  35838. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35839. }
  35840. if (parsedVertexData.hasUVs3) {
  35841. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35842. }
  35843. if (parsedVertexData.hasUVs4) {
  35844. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35845. }
  35846. if (parsedVertexData.hasUVs5) {
  35847. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35848. }
  35849. if (parsedVertexData.hasUVs6) {
  35850. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35851. }
  35852. if (parsedVertexData.hasColors) {
  35853. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35854. }
  35855. if (parsedVertexData.hasMatricesIndices) {
  35856. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35857. }
  35858. if (parsedVertexData.hasMatricesWeights) {
  35859. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35860. }
  35861. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35862. }
  35863. else {
  35864. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35865. }
  35866. scene.pushGeometry(geometry, true);
  35867. return geometry;
  35868. };
  35869. return Geometry;
  35870. }());
  35871. BABYLON.Geometry = Geometry;
  35872. // Primitives
  35873. /// Abstract class
  35874. /**
  35875. * Abstract class used to provide common services for all typed geometries
  35876. */
  35877. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35878. __extends(_PrimitiveGeometry, _super);
  35879. /**
  35880. * Creates a new typed geometry
  35881. * @param id defines the unique ID of the geometry
  35882. * @param scene defines the hosting scene
  35883. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35884. * @param mesh defines the hosting mesh (can be null)
  35885. */
  35886. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35887. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35888. if (mesh === void 0) { mesh = null; }
  35889. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35890. _this._canBeRegenerated = _canBeRegenerated;
  35891. _this._beingRegenerated = true;
  35892. _this.regenerate();
  35893. _this._beingRegenerated = false;
  35894. return _this;
  35895. }
  35896. /**
  35897. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35898. * @returns true if the geometry can be regenerated
  35899. */
  35900. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35901. return this._canBeRegenerated;
  35902. };
  35903. /**
  35904. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35905. */
  35906. _PrimitiveGeometry.prototype.regenerate = function () {
  35907. if (!this._canBeRegenerated) {
  35908. return;
  35909. }
  35910. this._beingRegenerated = true;
  35911. this.setAllVerticesData(this._regenerateVertexData(), false);
  35912. this._beingRegenerated = false;
  35913. };
  35914. /**
  35915. * Clone the geometry
  35916. * @param id defines the unique ID of the new geometry
  35917. * @returns the new geometry
  35918. */
  35919. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35920. return _super.prototype.copy.call(this, id);
  35921. };
  35922. // overrides
  35923. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35924. if (!this._beingRegenerated) {
  35925. return;
  35926. }
  35927. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35928. };
  35929. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35930. if (!this._beingRegenerated) {
  35931. return;
  35932. }
  35933. _super.prototype.setVerticesData.call(this, kind, data, false);
  35934. };
  35935. // to override
  35936. /** @ignore */
  35937. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35938. throw new Error("Abstract method");
  35939. };
  35940. _PrimitiveGeometry.prototype.copy = function (id) {
  35941. throw new Error("Must be overriden in sub-classes.");
  35942. };
  35943. _PrimitiveGeometry.prototype.serialize = function () {
  35944. var serializationObject = _super.prototype.serialize.call(this);
  35945. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35946. return serializationObject;
  35947. };
  35948. return _PrimitiveGeometry;
  35949. }(Geometry));
  35950. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35951. /**
  35952. * Creates a ribbon geometry
  35953. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35954. */
  35955. var RibbonGeometry = /** @class */ (function (_super) {
  35956. __extends(RibbonGeometry, _super);
  35957. /**
  35958. * Creates a ribbon geometry
  35959. * @param id defines the unique ID of the geometry
  35960. * @param scene defines the hosting scene
  35961. * @param pathArray defines the array of paths to use
  35962. * @param closeArray defines if the last path and the first path must be joined
  35963. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35964. * @param offset defines the offset between points
  35965. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35966. * @param mesh defines the hosting mesh (can be null)
  35967. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35968. */
  35969. function RibbonGeometry(id, scene,
  35970. /**
  35971. * Defines the array of paths to use
  35972. */
  35973. pathArray,
  35974. /**
  35975. * Defines if the last and first points of each path in your pathArray must be joined
  35976. */
  35977. closeArray,
  35978. /**
  35979. * Defines if the last and first points of each path in your pathArray must be joined
  35980. */
  35981. closePath,
  35982. /**
  35983. * Defines the offset between points
  35984. */
  35985. offset, canBeRegenerated, mesh,
  35986. /**
  35987. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35988. */
  35989. side) {
  35990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35991. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35992. _this.pathArray = pathArray;
  35993. _this.closeArray = closeArray;
  35994. _this.closePath = closePath;
  35995. _this.offset = offset;
  35996. _this.side = side;
  35997. return _this;
  35998. }
  35999. /** @ignore */
  36000. RibbonGeometry.prototype._regenerateVertexData = function () {
  36001. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36002. };
  36003. RibbonGeometry.prototype.copy = function (id) {
  36004. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36005. };
  36006. return RibbonGeometry;
  36007. }(_PrimitiveGeometry));
  36008. BABYLON.RibbonGeometry = RibbonGeometry;
  36009. /**
  36010. * Creates a box geometry
  36011. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36012. */
  36013. var BoxGeometry = /** @class */ (function (_super) {
  36014. __extends(BoxGeometry, _super);
  36015. /**
  36016. * Creates a box geometry
  36017. * @param id defines the unique ID of the geometry
  36018. * @param scene defines the hosting scene
  36019. * @param size defines the zise of the box (width, height and depth are the same)
  36020. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36021. * @param mesh defines the hosting mesh (can be null)
  36022. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36023. */
  36024. function BoxGeometry(id, scene,
  36025. /**
  36026. * Defines the zise of the box (width, height and depth are the same)
  36027. */
  36028. size, canBeRegenerated, mesh,
  36029. /**
  36030. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36031. */
  36032. side) {
  36033. if (mesh === void 0) { mesh = null; }
  36034. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36035. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36036. _this.size = size;
  36037. _this.side = side;
  36038. return _this;
  36039. }
  36040. BoxGeometry.prototype._regenerateVertexData = function () {
  36041. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36042. };
  36043. BoxGeometry.prototype.copy = function (id) {
  36044. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36045. };
  36046. BoxGeometry.prototype.serialize = function () {
  36047. var serializationObject = _super.prototype.serialize.call(this);
  36048. serializationObject.size = this.size;
  36049. return serializationObject;
  36050. };
  36051. BoxGeometry.Parse = function (parsedBox, scene) {
  36052. if (scene.getGeometryByID(parsedBox.id)) {
  36053. return null; // null since geometry could be something else than a box...
  36054. }
  36055. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36056. if (BABYLON.Tags) {
  36057. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36058. }
  36059. scene.pushGeometry(box, true);
  36060. return box;
  36061. };
  36062. return BoxGeometry;
  36063. }(_PrimitiveGeometry));
  36064. BABYLON.BoxGeometry = BoxGeometry;
  36065. /**
  36066. * Creates a sphere geometry
  36067. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36068. */
  36069. var SphereGeometry = /** @class */ (function (_super) {
  36070. __extends(SphereGeometry, _super);
  36071. /**
  36072. * Create a new sphere geometry
  36073. * @param id defines the unique ID of the geometry
  36074. * @param scene defines the hosting scene
  36075. * @param segments defines the number of segments to use to create the sphere
  36076. * @param diameter defines the diameter of the sphere
  36077. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36078. * @param mesh defines the hosting mesh (can be null)
  36079. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36080. */
  36081. function SphereGeometry(id, scene,
  36082. /**
  36083. * Defines the number of segments to use to create the sphere
  36084. */
  36085. segments,
  36086. /**
  36087. * Defines the diameter of the sphere
  36088. */
  36089. diameter, canBeRegenerated, mesh,
  36090. /**
  36091. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36092. */
  36093. side) {
  36094. if (mesh === void 0) { mesh = null; }
  36095. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36096. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36097. _this.segments = segments;
  36098. _this.diameter = diameter;
  36099. _this.side = side;
  36100. return _this;
  36101. }
  36102. SphereGeometry.prototype._regenerateVertexData = function () {
  36103. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36104. };
  36105. SphereGeometry.prototype.copy = function (id) {
  36106. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36107. };
  36108. SphereGeometry.prototype.serialize = function () {
  36109. var serializationObject = _super.prototype.serialize.call(this);
  36110. serializationObject.segments = this.segments;
  36111. serializationObject.diameter = this.diameter;
  36112. return serializationObject;
  36113. };
  36114. SphereGeometry.Parse = function (parsedSphere, scene) {
  36115. if (scene.getGeometryByID(parsedSphere.id)) {
  36116. return null; // null since geometry could be something else than a sphere...
  36117. }
  36118. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36119. if (BABYLON.Tags) {
  36120. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36121. }
  36122. scene.pushGeometry(sphere, true);
  36123. return sphere;
  36124. };
  36125. return SphereGeometry;
  36126. }(_PrimitiveGeometry));
  36127. BABYLON.SphereGeometry = SphereGeometry;
  36128. /**
  36129. * Creates a disc geometry
  36130. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36131. */
  36132. var DiscGeometry = /** @class */ (function (_super) {
  36133. __extends(DiscGeometry, _super);
  36134. /**
  36135. * Creates a new disc geometry
  36136. * @param id defines the unique ID of the geometry
  36137. * @param scene defines the hosting scene
  36138. * @param radius defines the radius of the disc
  36139. * @param tessellation defines the tesselation factor to apply to the disc
  36140. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36141. * @param mesh defines the hosting mesh (can be null)
  36142. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36143. */
  36144. function DiscGeometry(id, scene,
  36145. /**
  36146. * Defines the radius of the disc
  36147. */
  36148. radius,
  36149. /**
  36150. * Defines the tesselation factor to apply to the disc
  36151. */
  36152. tessellation, canBeRegenerated, mesh,
  36153. /**
  36154. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36155. */
  36156. side) {
  36157. if (mesh === void 0) { mesh = null; }
  36158. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36159. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36160. _this.radius = radius;
  36161. _this.tessellation = tessellation;
  36162. _this.side = side;
  36163. return _this;
  36164. }
  36165. DiscGeometry.prototype._regenerateVertexData = function () {
  36166. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36167. };
  36168. DiscGeometry.prototype.copy = function (id) {
  36169. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36170. };
  36171. return DiscGeometry;
  36172. }(_PrimitiveGeometry));
  36173. BABYLON.DiscGeometry = DiscGeometry;
  36174. /**
  36175. * Creates a new cylinder geometry
  36176. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36177. */
  36178. var CylinderGeometry = /** @class */ (function (_super) {
  36179. __extends(CylinderGeometry, _super);
  36180. /**
  36181. * Creates a new cylinder geometry
  36182. * @param id defines the unique ID of the geometry
  36183. * @param scene defines the hosting scene
  36184. * @param height defines the height of the cylinder
  36185. * @param diameterTop defines the diameter of the cylinder's top cap
  36186. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36187. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36188. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36189. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36190. * @param mesh defines the hosting mesh (can be null)
  36191. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36192. */
  36193. function CylinderGeometry(id, scene,
  36194. /**
  36195. * Defines the height of the cylinder
  36196. */
  36197. height,
  36198. /**
  36199. * Defines the diameter of the cylinder's top cap
  36200. */
  36201. diameterTop,
  36202. /**
  36203. * Defines the diameter of the cylinder's bottom cap
  36204. */
  36205. diameterBottom,
  36206. /**
  36207. * Defines the tessellation factor to apply to the cylinder
  36208. */
  36209. tessellation,
  36210. /**
  36211. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36212. */
  36213. subdivisions, canBeRegenerated, mesh,
  36214. /**
  36215. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36216. */
  36217. side) {
  36218. if (subdivisions === void 0) { subdivisions = 1; }
  36219. if (mesh === void 0) { mesh = null; }
  36220. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36221. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36222. _this.height = height;
  36223. _this.diameterTop = diameterTop;
  36224. _this.diameterBottom = diameterBottom;
  36225. _this.tessellation = tessellation;
  36226. _this.subdivisions = subdivisions;
  36227. _this.side = side;
  36228. return _this;
  36229. }
  36230. CylinderGeometry.prototype._regenerateVertexData = function () {
  36231. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36232. };
  36233. CylinderGeometry.prototype.copy = function (id) {
  36234. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36235. };
  36236. CylinderGeometry.prototype.serialize = function () {
  36237. var serializationObject = _super.prototype.serialize.call(this);
  36238. serializationObject.height = this.height;
  36239. serializationObject.diameterTop = this.diameterTop;
  36240. serializationObject.diameterBottom = this.diameterBottom;
  36241. serializationObject.tessellation = this.tessellation;
  36242. return serializationObject;
  36243. };
  36244. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36245. if (scene.getGeometryByID(parsedCylinder.id)) {
  36246. return null; // null since geometry could be something else than a cylinder...
  36247. }
  36248. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36249. if (BABYLON.Tags) {
  36250. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36251. }
  36252. scene.pushGeometry(cylinder, true);
  36253. return cylinder;
  36254. };
  36255. return CylinderGeometry;
  36256. }(_PrimitiveGeometry));
  36257. BABYLON.CylinderGeometry = CylinderGeometry;
  36258. /**
  36259. * Creates a new torus geometry
  36260. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36261. */
  36262. var TorusGeometry = /** @class */ (function (_super) {
  36263. __extends(TorusGeometry, _super);
  36264. /**
  36265. * Creates a new torus geometry
  36266. * @param id defines the unique ID of the geometry
  36267. * @param scene defines the hosting scene
  36268. * @param diameter defines the diameter of the torus
  36269. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36270. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36271. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36272. * @param mesh defines the hosting mesh (can be null)
  36273. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36274. */
  36275. function TorusGeometry(id, scene,
  36276. /**
  36277. * Defines the diameter of the torus
  36278. */
  36279. diameter,
  36280. /**
  36281. * Defines the thickness of the torus (ie. internal diameter)
  36282. */
  36283. thickness,
  36284. /**
  36285. * Defines the tesselation factor to apply to the torus
  36286. */
  36287. tessellation, canBeRegenerated, mesh,
  36288. /**
  36289. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36290. */
  36291. side) {
  36292. if (mesh === void 0) { mesh = null; }
  36293. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36294. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36295. _this.diameter = diameter;
  36296. _this.thickness = thickness;
  36297. _this.tessellation = tessellation;
  36298. _this.side = side;
  36299. return _this;
  36300. }
  36301. TorusGeometry.prototype._regenerateVertexData = function () {
  36302. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36303. };
  36304. TorusGeometry.prototype.copy = function (id) {
  36305. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36306. };
  36307. TorusGeometry.prototype.serialize = function () {
  36308. var serializationObject = _super.prototype.serialize.call(this);
  36309. serializationObject.diameter = this.diameter;
  36310. serializationObject.thickness = this.thickness;
  36311. serializationObject.tessellation = this.tessellation;
  36312. return serializationObject;
  36313. };
  36314. TorusGeometry.Parse = function (parsedTorus, scene) {
  36315. if (scene.getGeometryByID(parsedTorus.id)) {
  36316. return null; // null since geometry could be something else than a torus...
  36317. }
  36318. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36319. if (BABYLON.Tags) {
  36320. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36321. }
  36322. scene.pushGeometry(torus, true);
  36323. return torus;
  36324. };
  36325. return TorusGeometry;
  36326. }(_PrimitiveGeometry));
  36327. BABYLON.TorusGeometry = TorusGeometry;
  36328. /**
  36329. * Creates a new ground geometry
  36330. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36331. */
  36332. var GroundGeometry = /** @class */ (function (_super) {
  36333. __extends(GroundGeometry, _super);
  36334. /**
  36335. * Creates a new ground geometry
  36336. * @param id defines the unique ID of the geometry
  36337. * @param scene defines the hosting scene
  36338. * @param width defines the width of the ground
  36339. * @param height defines the height of the ground
  36340. * @param subdivisions defines the subdivisions to apply to the ground
  36341. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36342. * @param mesh defines the hosting mesh (can be null)
  36343. */
  36344. function GroundGeometry(id, scene,
  36345. /**
  36346. * Defines the width of the ground
  36347. */
  36348. width,
  36349. /**
  36350. * Defines the height of the ground
  36351. */
  36352. height,
  36353. /**
  36354. * Defines the subdivisions to apply to the ground
  36355. */
  36356. subdivisions, canBeRegenerated, mesh) {
  36357. if (mesh === void 0) { mesh = null; }
  36358. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36359. _this.width = width;
  36360. _this.height = height;
  36361. _this.subdivisions = subdivisions;
  36362. return _this;
  36363. }
  36364. GroundGeometry.prototype._regenerateVertexData = function () {
  36365. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36366. };
  36367. GroundGeometry.prototype.copy = function (id) {
  36368. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36369. };
  36370. GroundGeometry.prototype.serialize = function () {
  36371. var serializationObject = _super.prototype.serialize.call(this);
  36372. serializationObject.width = this.width;
  36373. serializationObject.height = this.height;
  36374. serializationObject.subdivisions = this.subdivisions;
  36375. return serializationObject;
  36376. };
  36377. GroundGeometry.Parse = function (parsedGround, scene) {
  36378. if (scene.getGeometryByID(parsedGround.id)) {
  36379. return null; // null since geometry could be something else than a ground...
  36380. }
  36381. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36382. if (BABYLON.Tags) {
  36383. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36384. }
  36385. scene.pushGeometry(ground, true);
  36386. return ground;
  36387. };
  36388. return GroundGeometry;
  36389. }(_PrimitiveGeometry));
  36390. BABYLON.GroundGeometry = GroundGeometry;
  36391. /**
  36392. * Creates a tiled ground geometry
  36393. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36394. */
  36395. var TiledGroundGeometry = /** @class */ (function (_super) {
  36396. __extends(TiledGroundGeometry, _super);
  36397. /**
  36398. * Creates a tiled ground geometry
  36399. * @param id defines the unique ID of the geometry
  36400. * @param scene defines the hosting scene
  36401. * @param xmin defines the minimum value on X axis
  36402. * @param zmin defines the minimum value on Z axis
  36403. * @param xmax defines the maximum value on X axis
  36404. * @param zmax defines the maximum value on Z axis
  36405. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36406. * @param precision defines the precision to use when computing the tiles
  36407. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36408. * @param mesh defines the hosting mesh (can be null)
  36409. */
  36410. function TiledGroundGeometry(id, scene,
  36411. /**
  36412. * Defines the minimum value on X axis
  36413. */
  36414. xmin,
  36415. /**
  36416. * Defines the minimum value on Z axis
  36417. */
  36418. zmin,
  36419. /**
  36420. * Defines the maximum value on X axis
  36421. */
  36422. xmax,
  36423. /**
  36424. * Defines the maximum value on Z axis
  36425. */
  36426. zmax,
  36427. /**
  36428. * Defines the subdivisions to apply to the ground
  36429. */
  36430. subdivisions,
  36431. /**
  36432. * Defines the precision to use when computing the tiles
  36433. */
  36434. precision, canBeRegenerated, mesh) {
  36435. if (mesh === void 0) { mesh = null; }
  36436. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36437. _this.xmin = xmin;
  36438. _this.zmin = zmin;
  36439. _this.xmax = xmax;
  36440. _this.zmax = zmax;
  36441. _this.subdivisions = subdivisions;
  36442. _this.precision = precision;
  36443. return _this;
  36444. }
  36445. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36446. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36447. };
  36448. TiledGroundGeometry.prototype.copy = function (id) {
  36449. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36450. };
  36451. return TiledGroundGeometry;
  36452. }(_PrimitiveGeometry));
  36453. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36454. /**
  36455. * Creates a plane geometry
  36456. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36457. */
  36458. var PlaneGeometry = /** @class */ (function (_super) {
  36459. __extends(PlaneGeometry, _super);
  36460. /**
  36461. * Creates a plane geometry
  36462. * @param id defines the unique ID of the geometry
  36463. * @param scene defines the hosting scene
  36464. * @param size defines the size of the plane (width === height)
  36465. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36466. * @param mesh defines the hosting mesh (can be null)
  36467. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36468. */
  36469. function PlaneGeometry(id, scene,
  36470. /**
  36471. * Defines the size of the plane (width === height)
  36472. */
  36473. size, canBeRegenerated, mesh,
  36474. /**
  36475. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36476. */
  36477. side) {
  36478. if (mesh === void 0) { mesh = null; }
  36479. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36480. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36481. _this.size = size;
  36482. _this.side = side;
  36483. return _this;
  36484. }
  36485. PlaneGeometry.prototype._regenerateVertexData = function () {
  36486. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36487. };
  36488. PlaneGeometry.prototype.copy = function (id) {
  36489. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36490. };
  36491. PlaneGeometry.prototype.serialize = function () {
  36492. var serializationObject = _super.prototype.serialize.call(this);
  36493. serializationObject.size = this.size;
  36494. return serializationObject;
  36495. };
  36496. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36497. if (scene.getGeometryByID(parsedPlane.id)) {
  36498. return null; // null since geometry could be something else than a ground...
  36499. }
  36500. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36501. if (BABYLON.Tags) {
  36502. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36503. }
  36504. scene.pushGeometry(plane, true);
  36505. return plane;
  36506. };
  36507. return PlaneGeometry;
  36508. }(_PrimitiveGeometry));
  36509. BABYLON.PlaneGeometry = PlaneGeometry;
  36510. /**
  36511. * Creates a torus knot geometry
  36512. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36513. */
  36514. var TorusKnotGeometry = /** @class */ (function (_super) {
  36515. __extends(TorusKnotGeometry, _super);
  36516. /**
  36517. * Creates a torus knot geometry
  36518. * @param id defines the unique ID of the geometry
  36519. * @param scene defines the hosting scene
  36520. * @param radius defines the radius of the torus knot
  36521. * @param tube defines the thickness of the torus knot tube
  36522. * @param radialSegments defines the number of radial segments
  36523. * @param tubularSegments defines the number of tubular segments
  36524. * @param p defines the first number of windings
  36525. * @param q defines the second number of windings
  36526. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36527. * @param mesh defines the hosting mesh (can be null)
  36528. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36529. */
  36530. function TorusKnotGeometry(id, scene,
  36531. /**
  36532. * Defines the radius of the torus knot
  36533. */
  36534. radius,
  36535. /**
  36536. * Defines the thickness of the torus knot tube
  36537. */
  36538. tube,
  36539. /**
  36540. * Defines the number of radial segments
  36541. */
  36542. radialSegments,
  36543. /**
  36544. * Defines the number of tubular segments
  36545. */
  36546. tubularSegments,
  36547. /**
  36548. * Defines the first number of windings
  36549. */
  36550. p,
  36551. /**
  36552. * Defines the second number of windings
  36553. */
  36554. q, canBeRegenerated, mesh,
  36555. /**
  36556. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36557. */
  36558. side) {
  36559. if (mesh === void 0) { mesh = null; }
  36560. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36561. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36562. _this.radius = radius;
  36563. _this.tube = tube;
  36564. _this.radialSegments = radialSegments;
  36565. _this.tubularSegments = tubularSegments;
  36566. _this.p = p;
  36567. _this.q = q;
  36568. _this.side = side;
  36569. return _this;
  36570. }
  36571. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36572. 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 });
  36573. };
  36574. TorusKnotGeometry.prototype.copy = function (id) {
  36575. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36576. };
  36577. TorusKnotGeometry.prototype.serialize = function () {
  36578. var serializationObject = _super.prototype.serialize.call(this);
  36579. serializationObject.radius = this.radius;
  36580. serializationObject.tube = this.tube;
  36581. serializationObject.radialSegments = this.radialSegments;
  36582. serializationObject.tubularSegments = this.tubularSegments;
  36583. serializationObject.p = this.p;
  36584. serializationObject.q = this.q;
  36585. return serializationObject;
  36586. };
  36587. ;
  36588. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36589. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36590. return null; // null since geometry could be something else than a ground...
  36591. }
  36592. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36593. if (BABYLON.Tags) {
  36594. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36595. }
  36596. scene.pushGeometry(torusKnot, true);
  36597. return torusKnot;
  36598. };
  36599. return TorusKnotGeometry;
  36600. }(_PrimitiveGeometry));
  36601. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36602. //}
  36603. })(BABYLON || (BABYLON = {}));
  36604. //# sourceMappingURL=babylon.geometry.js.map
  36605. var BABYLON;
  36606. (function (BABYLON) {
  36607. /**
  36608. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36609. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36610. */
  36611. var PostProcessManager = /** @class */ (function () {
  36612. /**
  36613. * Creates a new instance of @see PostProcess
  36614. * @param scene The scene that the post process is associated with.
  36615. */
  36616. function PostProcessManager(scene) {
  36617. this._vertexBuffers = {};
  36618. this._scene = scene;
  36619. }
  36620. PostProcessManager.prototype._prepareBuffers = function () {
  36621. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36622. return;
  36623. }
  36624. // VBO
  36625. var vertices = [];
  36626. vertices.push(1, 1);
  36627. vertices.push(-1, 1);
  36628. vertices.push(-1, -1);
  36629. vertices.push(1, -1);
  36630. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36631. this._buildIndexBuffer();
  36632. };
  36633. PostProcessManager.prototype._buildIndexBuffer = function () {
  36634. // Indices
  36635. var indices = [];
  36636. indices.push(0);
  36637. indices.push(1);
  36638. indices.push(2);
  36639. indices.push(0);
  36640. indices.push(2);
  36641. indices.push(3);
  36642. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36643. };
  36644. /**
  36645. * Rebuilds the vertex buffers of the manager.
  36646. */
  36647. PostProcessManager.prototype._rebuild = function () {
  36648. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36649. if (!vb) {
  36650. return;
  36651. }
  36652. vb._rebuild();
  36653. this._buildIndexBuffer();
  36654. };
  36655. // Methods
  36656. /**
  36657. * Prepares a frame to be run through a post process.
  36658. * @param sourceTexture The input texture to the post procesess. (default: null)
  36659. * @param postProcesses An array of post processes to be run. (default: null)
  36660. * @returns True if the post processes were able to be run.
  36661. */
  36662. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36663. if (sourceTexture === void 0) { sourceTexture = null; }
  36664. if (postProcesses === void 0) { postProcesses = null; }
  36665. var camera = this._scene.activeCamera;
  36666. if (!camera) {
  36667. return false;
  36668. }
  36669. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36670. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36671. return false;
  36672. }
  36673. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36674. return true;
  36675. };
  36676. /**
  36677. * Manually render a set of post processes to a texture.
  36678. * @param postProcesses An array of post processes to be run.
  36679. * @param targetTexture The target texture to render to.
  36680. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36681. */
  36682. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36683. if (targetTexture === void 0) { targetTexture = null; }
  36684. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36685. var engine = this._scene.getEngine();
  36686. for (var index = 0; index < postProcesses.length; index++) {
  36687. if (index < postProcesses.length - 1) {
  36688. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36689. }
  36690. else {
  36691. if (targetTexture) {
  36692. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36693. }
  36694. else {
  36695. engine.restoreDefaultFramebuffer();
  36696. }
  36697. }
  36698. var pp = postProcesses[index];
  36699. var effect = pp.apply();
  36700. if (effect) {
  36701. pp.onBeforeRenderObservable.notifyObservers(effect);
  36702. // VBOs
  36703. this._prepareBuffers();
  36704. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36705. // Draw order
  36706. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36707. pp.onAfterRenderObservable.notifyObservers(effect);
  36708. }
  36709. }
  36710. // Restore depth buffer
  36711. engine.setDepthBuffer(true);
  36712. engine.setDepthWrite(true);
  36713. };
  36714. /**
  36715. * Finalize the result of the output of the postprocesses.
  36716. * @param doNotPresent If true the result will not be displayed to the screen.
  36717. * @param targetTexture The target texture to render to.
  36718. * @param faceIndex The index of the face to bind the target texture to.
  36719. * @param postProcesses The array of post processes to render.
  36720. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36721. */
  36722. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36723. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36724. var camera = this._scene.activeCamera;
  36725. if (!camera) {
  36726. return;
  36727. }
  36728. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36729. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36730. return;
  36731. }
  36732. var engine = this._scene.getEngine();
  36733. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36734. if (index < len - 1) {
  36735. postProcesses[index + 1].activate(camera, targetTexture);
  36736. }
  36737. else {
  36738. if (targetTexture) {
  36739. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36740. }
  36741. else {
  36742. engine.restoreDefaultFramebuffer();
  36743. }
  36744. }
  36745. if (doNotPresent) {
  36746. break;
  36747. }
  36748. var pp = postProcesses[index];
  36749. var effect = pp.apply();
  36750. if (effect) {
  36751. pp.onBeforeRenderObservable.notifyObservers(effect);
  36752. // VBOs
  36753. this._prepareBuffers();
  36754. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36755. // Draw order
  36756. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36757. pp.onAfterRenderObservable.notifyObservers(effect);
  36758. }
  36759. }
  36760. // Restore states
  36761. engine.setDepthBuffer(true);
  36762. engine.setDepthWrite(true);
  36763. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36764. };
  36765. /**
  36766. * Disposes of the post process manager.
  36767. */
  36768. PostProcessManager.prototype.dispose = function () {
  36769. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36770. if (buffer) {
  36771. buffer.dispose();
  36772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36773. }
  36774. if (this._indexBuffer) {
  36775. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36776. this._indexBuffer = null;
  36777. }
  36778. };
  36779. return PostProcessManager;
  36780. }());
  36781. BABYLON.PostProcessManager = PostProcessManager;
  36782. })(BABYLON || (BABYLON = {}));
  36783. //# sourceMappingURL=babylon.postProcessManager.js.map
  36784. var BABYLON;
  36785. (function (BABYLON) {
  36786. /**
  36787. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36788. */
  36789. var PerformanceMonitor = /** @class */ (function () {
  36790. /**
  36791. * constructor
  36792. * @param frameSampleSize The number of samples required to saturate the sliding window
  36793. */
  36794. function PerformanceMonitor(frameSampleSize) {
  36795. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36796. this._enabled = true;
  36797. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36798. }
  36799. /**
  36800. * Samples current frame
  36801. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36802. */
  36803. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36804. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36805. if (!this._enabled)
  36806. return;
  36807. if (this._lastFrameTimeMs != null) {
  36808. var dt = timeMs - this._lastFrameTimeMs;
  36809. this._rollingFrameTime.add(dt);
  36810. }
  36811. this._lastFrameTimeMs = timeMs;
  36812. };
  36813. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36814. /**
  36815. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36816. * @return Average frame time in milliseconds
  36817. */
  36818. get: function () {
  36819. return this._rollingFrameTime.average;
  36820. },
  36821. enumerable: true,
  36822. configurable: true
  36823. });
  36824. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36825. /**
  36826. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36827. * @return Frame time variance in milliseconds squared
  36828. */
  36829. get: function () {
  36830. return this._rollingFrameTime.variance;
  36831. },
  36832. enumerable: true,
  36833. configurable: true
  36834. });
  36835. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36836. /**
  36837. * Returns the frame time of the most recent frame
  36838. * @return Frame time in milliseconds
  36839. */
  36840. get: function () {
  36841. return this._rollingFrameTime.history(0);
  36842. },
  36843. enumerable: true,
  36844. configurable: true
  36845. });
  36846. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36847. /**
  36848. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36849. * @return Framerate in frames per second
  36850. */
  36851. get: function () {
  36852. return 1000.0 / this._rollingFrameTime.average;
  36853. },
  36854. enumerable: true,
  36855. configurable: true
  36856. });
  36857. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36858. /**
  36859. * Returns the average framerate in frames per second using the most recent frame time
  36860. * @return Framerate in frames per second
  36861. */
  36862. get: function () {
  36863. var history = this._rollingFrameTime.history(0);
  36864. if (history === 0) {
  36865. return 0;
  36866. }
  36867. return 1000.0 / history;
  36868. },
  36869. enumerable: true,
  36870. configurable: true
  36871. });
  36872. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36873. /**
  36874. * Returns true if enough samples have been taken to completely fill the sliding window
  36875. * @return true if saturated
  36876. */
  36877. get: function () {
  36878. return this._rollingFrameTime.isSaturated();
  36879. },
  36880. enumerable: true,
  36881. configurable: true
  36882. });
  36883. /**
  36884. * Enables contributions to the sliding window sample set
  36885. */
  36886. PerformanceMonitor.prototype.enable = function () {
  36887. this._enabled = true;
  36888. };
  36889. /**
  36890. * Disables contributions to the sliding window sample set
  36891. * Samples will not be interpolated over the disabled period
  36892. */
  36893. PerformanceMonitor.prototype.disable = function () {
  36894. this._enabled = false;
  36895. //clear last sample to avoid interpolating over the disabled period when next enabled
  36896. this._lastFrameTimeMs = null;
  36897. };
  36898. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36899. /**
  36900. * Returns true if sampling is enabled
  36901. * @return true if enabled
  36902. */
  36903. get: function () {
  36904. return this._enabled;
  36905. },
  36906. enumerable: true,
  36907. configurable: true
  36908. });
  36909. /**
  36910. * Resets performance monitor
  36911. */
  36912. PerformanceMonitor.prototype.reset = function () {
  36913. //clear last sample to avoid interpolating over the disabled period when next enabled
  36914. this._lastFrameTimeMs = null;
  36915. //wipe record
  36916. this._rollingFrameTime.reset();
  36917. };
  36918. return PerformanceMonitor;
  36919. }());
  36920. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36921. /**
  36922. * RollingAverage
  36923. *
  36924. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36925. */
  36926. var RollingAverage = /** @class */ (function () {
  36927. /**
  36928. * constructor
  36929. * @param length The number of samples required to saturate the sliding window
  36930. */
  36931. function RollingAverage(length) {
  36932. this._samples = new Array(length);
  36933. this.reset();
  36934. }
  36935. /**
  36936. * Adds a sample to the sample set
  36937. * @param v The sample value
  36938. */
  36939. RollingAverage.prototype.add = function (v) {
  36940. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36941. var delta;
  36942. //we need to check if we've already wrapped round
  36943. if (this.isSaturated()) {
  36944. //remove bottom of stack from mean
  36945. var bottomValue = this._samples[this._pos];
  36946. delta = bottomValue - this.average;
  36947. this.average -= delta / (this._sampleCount - 1);
  36948. this._m2 -= delta * (bottomValue - this.average);
  36949. }
  36950. else {
  36951. this._sampleCount++;
  36952. }
  36953. //add new value to mean
  36954. delta = v - this.average;
  36955. this.average += delta / (this._sampleCount);
  36956. this._m2 += delta * (v - this.average);
  36957. //set the new variance
  36958. this.variance = this._m2 / (this._sampleCount - 1);
  36959. this._samples[this._pos] = v;
  36960. this._pos++;
  36961. this._pos %= this._samples.length; //positive wrap around
  36962. };
  36963. /**
  36964. * Returns previously added values or null if outside of history or outside the sliding window domain
  36965. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36966. * @return Value previously recorded with add() or null if outside of range
  36967. */
  36968. RollingAverage.prototype.history = function (i) {
  36969. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36970. return 0;
  36971. }
  36972. var i0 = this._wrapPosition(this._pos - 1.0);
  36973. return this._samples[this._wrapPosition(i0 - i)];
  36974. };
  36975. /**
  36976. * Returns true if enough samples have been taken to completely fill the sliding window
  36977. * @return true if sample-set saturated
  36978. */
  36979. RollingAverage.prototype.isSaturated = function () {
  36980. return this._sampleCount >= this._samples.length;
  36981. };
  36982. /**
  36983. * Resets the rolling average (equivalent to 0 samples taken so far)
  36984. */
  36985. RollingAverage.prototype.reset = function () {
  36986. this.average = 0;
  36987. this.variance = 0;
  36988. this._sampleCount = 0;
  36989. this._pos = 0;
  36990. this._m2 = 0;
  36991. };
  36992. /**
  36993. * Wraps a value around the sample range boundaries
  36994. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36995. * @return Wrapped position in sample range
  36996. */
  36997. RollingAverage.prototype._wrapPosition = function (i) {
  36998. var max = this._samples.length;
  36999. return ((i % max) + max) % max;
  37000. };
  37001. return RollingAverage;
  37002. }());
  37003. BABYLON.RollingAverage = RollingAverage;
  37004. })(BABYLON || (BABYLON = {}));
  37005. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37006. var BABYLON;
  37007. (function (BABYLON) {
  37008. /**
  37009. * This groups together the common properties used for image processing either in direct forward pass
  37010. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37011. * or not.
  37012. */
  37013. var ImageProcessingConfiguration = /** @class */ (function () {
  37014. function ImageProcessingConfiguration() {
  37015. /**
  37016. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37017. */
  37018. this.colorCurves = new BABYLON.ColorCurves();
  37019. this._colorCurvesEnabled = false;
  37020. this._colorGradingEnabled = false;
  37021. this._colorGradingWithGreenDepth = true;
  37022. this._colorGradingBGR = true;
  37023. this._exposure = 1.0;
  37024. this._toneMappingEnabled = false;
  37025. this._contrast = 1.0;
  37026. /**
  37027. * Vignette stretch size.
  37028. */
  37029. this.vignetteStretch = 0;
  37030. /**
  37031. * Vignette centre X Offset.
  37032. */
  37033. this.vignetteCentreX = 0;
  37034. /**
  37035. * Vignette centre Y Offset.
  37036. */
  37037. this.vignetteCentreY = 0;
  37038. /**
  37039. * Vignette weight or intensity of the vignette effect.
  37040. */
  37041. this.vignetteWeight = 1.5;
  37042. /**
  37043. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37044. * if vignetteEnabled is set to true.
  37045. */
  37046. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37047. /**
  37048. * Camera field of view used by the Vignette effect.
  37049. */
  37050. this.vignetteCameraFov = 0.5;
  37051. this._grainEnabled = false;
  37052. this._grainIntensity = 30;
  37053. this._grainAnimated = false;
  37054. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37055. this._vignetteEnabled = false;
  37056. this._applyByPostProcess = false;
  37057. this._isEnabled = true;
  37058. /**
  37059. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37060. * @type {BABYLON.Observable}
  37061. */
  37062. this.onUpdateParameters = new BABYLON.Observable();
  37063. }
  37064. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37065. /**
  37066. * Gets wether the color curves effect is enabled.
  37067. */
  37068. get: function () {
  37069. return this._colorCurvesEnabled;
  37070. },
  37071. /**
  37072. * Sets wether the color curves effect is enabled.
  37073. */
  37074. set: function (value) {
  37075. if (this._colorCurvesEnabled === value) {
  37076. return;
  37077. }
  37078. this._colorCurvesEnabled = value;
  37079. this._updateParameters();
  37080. },
  37081. enumerable: true,
  37082. configurable: true
  37083. });
  37084. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37085. /**
  37086. * Gets wether the color grading effect is enabled.
  37087. */
  37088. get: function () {
  37089. return this._colorGradingEnabled;
  37090. },
  37091. /**
  37092. * Sets wether the color grading effect is enabled.
  37093. */
  37094. set: function (value) {
  37095. if (this._colorGradingEnabled === value) {
  37096. return;
  37097. }
  37098. this._colorGradingEnabled = value;
  37099. this._updateParameters();
  37100. },
  37101. enumerable: true,
  37102. configurable: true
  37103. });
  37104. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37105. /**
  37106. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37107. */
  37108. get: function () {
  37109. return this._colorGradingWithGreenDepth;
  37110. },
  37111. /**
  37112. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37113. */
  37114. set: function (value) {
  37115. if (this._colorGradingWithGreenDepth === value) {
  37116. return;
  37117. }
  37118. this._colorGradingWithGreenDepth = value;
  37119. this._updateParameters();
  37120. },
  37121. enumerable: true,
  37122. configurable: true
  37123. });
  37124. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37125. /**
  37126. * Gets wether the color grading texture contains BGR values.
  37127. */
  37128. get: function () {
  37129. return this._colorGradingBGR;
  37130. },
  37131. /**
  37132. * Sets wether the color grading texture contains BGR values.
  37133. */
  37134. set: function (value) {
  37135. if (this._colorGradingBGR === value) {
  37136. return;
  37137. }
  37138. this._colorGradingBGR = value;
  37139. this._updateParameters();
  37140. },
  37141. enumerable: true,
  37142. configurable: true
  37143. });
  37144. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37145. /**
  37146. * Gets the Exposure used in the effect.
  37147. */
  37148. get: function () {
  37149. return this._exposure;
  37150. },
  37151. /**
  37152. * Sets the Exposure used in the effect.
  37153. */
  37154. set: function (value) {
  37155. if (this._exposure === value) {
  37156. return;
  37157. }
  37158. this._exposure = value;
  37159. this._updateParameters();
  37160. },
  37161. enumerable: true,
  37162. configurable: true
  37163. });
  37164. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37165. /**
  37166. * Gets wether the tone mapping effect is enabled.
  37167. */
  37168. get: function () {
  37169. return this._toneMappingEnabled;
  37170. },
  37171. /**
  37172. * Sets wether the tone mapping effect is enabled.
  37173. */
  37174. set: function (value) {
  37175. if (this._toneMappingEnabled === value) {
  37176. return;
  37177. }
  37178. this._toneMappingEnabled = value;
  37179. this._updateParameters();
  37180. },
  37181. enumerable: true,
  37182. configurable: true
  37183. });
  37184. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37185. /**
  37186. * Gets the contrast used in the effect.
  37187. */
  37188. get: function () {
  37189. return this._contrast;
  37190. },
  37191. /**
  37192. * Sets the contrast used in the effect.
  37193. */
  37194. set: function (value) {
  37195. if (this._contrast === value) {
  37196. return;
  37197. }
  37198. this._contrast = value;
  37199. this._updateParameters();
  37200. },
  37201. enumerable: true,
  37202. configurable: true
  37203. });
  37204. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37205. /**
  37206. * If the grain effect should be enabled.
  37207. */
  37208. get: function () {
  37209. return this._grainEnabled;
  37210. },
  37211. set: function (value) {
  37212. if (this._grainEnabled === value) {
  37213. return;
  37214. }
  37215. this._grainEnabled = value;
  37216. this._updateParameters();
  37217. },
  37218. enumerable: true,
  37219. configurable: true
  37220. });
  37221. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37222. /**
  37223. * Amount of grain to be applied by the grain effect.
  37224. */
  37225. get: function () {
  37226. return this._grainIntensity;
  37227. },
  37228. set: function (value) {
  37229. if (this._grainIntensity === value) {
  37230. return;
  37231. }
  37232. this._grainIntensity = value;
  37233. },
  37234. enumerable: true,
  37235. configurable: true
  37236. });
  37237. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37238. /**
  37239. * If the grain effect should be animated.
  37240. */
  37241. get: function () {
  37242. return this._grainAnimated;
  37243. },
  37244. set: function (value) {
  37245. if (this._grainAnimated === value) {
  37246. return;
  37247. }
  37248. this._grainAnimated = value;
  37249. this._updateParameters();
  37250. },
  37251. enumerable: true,
  37252. configurable: true
  37253. });
  37254. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37255. /**
  37256. * Gets the vignette blend mode allowing different kind of effect.
  37257. */
  37258. get: function () {
  37259. return this._vignetteBlendMode;
  37260. },
  37261. /**
  37262. * Sets the vignette blend mode allowing different kind of effect.
  37263. */
  37264. set: function (value) {
  37265. if (this._vignetteBlendMode === value) {
  37266. return;
  37267. }
  37268. this._vignetteBlendMode = value;
  37269. this._updateParameters();
  37270. },
  37271. enumerable: true,
  37272. configurable: true
  37273. });
  37274. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37275. /**
  37276. * Gets wether the vignette effect is enabled.
  37277. */
  37278. get: function () {
  37279. return this._vignetteEnabled;
  37280. },
  37281. /**
  37282. * Sets wether the vignette effect is enabled.
  37283. */
  37284. set: function (value) {
  37285. if (this._vignetteEnabled === value) {
  37286. return;
  37287. }
  37288. this._vignetteEnabled = value;
  37289. this._updateParameters();
  37290. },
  37291. enumerable: true,
  37292. configurable: true
  37293. });
  37294. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37295. /**
  37296. * Gets wether the image processing is applied through a post process or not.
  37297. */
  37298. get: function () {
  37299. return this._applyByPostProcess;
  37300. },
  37301. /**
  37302. * Sets wether the image processing is applied through a post process or not.
  37303. */
  37304. set: function (value) {
  37305. if (this._applyByPostProcess === value) {
  37306. return;
  37307. }
  37308. this._applyByPostProcess = value;
  37309. this._updateParameters();
  37310. },
  37311. enumerable: true,
  37312. configurable: true
  37313. });
  37314. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37315. /**
  37316. * Gets wether the image processing is enabled or not.
  37317. */
  37318. get: function () {
  37319. return this._isEnabled;
  37320. },
  37321. /**
  37322. * Sets wether the image processing is enabled or not.
  37323. */
  37324. set: function (value) {
  37325. if (this._isEnabled === value) {
  37326. return;
  37327. }
  37328. this._isEnabled = value;
  37329. this._updateParameters();
  37330. },
  37331. enumerable: true,
  37332. configurable: true
  37333. });
  37334. /**
  37335. * Method called each time the image processing information changes requires to recompile the effect.
  37336. */
  37337. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37338. this.onUpdateParameters.notifyObservers(this);
  37339. };
  37340. ImageProcessingConfiguration.prototype.getClassName = function () {
  37341. return "ImageProcessingConfiguration";
  37342. };
  37343. /**
  37344. * Prepare the list of uniforms associated with the Image Processing effects.
  37345. * @param uniformsList The list of uniforms used in the effect
  37346. * @param defines the list of defines currently in use
  37347. */
  37348. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37349. if (defines.EXPOSURE) {
  37350. uniforms.push("exposureLinear");
  37351. }
  37352. if (defines.CONTRAST) {
  37353. uniforms.push("contrast");
  37354. }
  37355. if (defines.COLORGRADING) {
  37356. uniforms.push("colorTransformSettings");
  37357. }
  37358. if (defines.VIGNETTE) {
  37359. uniforms.push("vInverseScreenSize");
  37360. uniforms.push("vignetteSettings1");
  37361. uniforms.push("vignetteSettings2");
  37362. }
  37363. if (defines.COLORCURVES) {
  37364. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37365. }
  37366. if (defines.GRAIN) {
  37367. uniforms.push("grainVarianceAmount");
  37368. uniforms.push("grainAnimatedSeed");
  37369. }
  37370. };
  37371. /**
  37372. * Prepare the list of samplers associated with the Image Processing effects.
  37373. * @param uniformsList The list of uniforms used in the effect
  37374. * @param defines the list of defines currently in use
  37375. */
  37376. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37377. if (defines.COLORGRADING) {
  37378. samplersList.push("txColorTransform");
  37379. }
  37380. };
  37381. /**
  37382. * Prepare the list of defines associated to the shader.
  37383. * @param defines the list of defines to complete
  37384. */
  37385. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37386. if (forPostProcess === void 0) { forPostProcess = false; }
  37387. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37388. defines.VIGNETTE = false;
  37389. defines.TONEMAPPING = false;
  37390. defines.CONTRAST = false;
  37391. defines.EXPOSURE = false;
  37392. defines.COLORCURVES = false;
  37393. defines.COLORGRADING = false;
  37394. defines.COLORGRADING3D = false;
  37395. defines.IMAGEPROCESSING = false;
  37396. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37397. return;
  37398. }
  37399. defines.VIGNETTE = this.vignetteEnabled;
  37400. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37401. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37402. defines.TONEMAPPING = this.toneMappingEnabled;
  37403. defines.CONTRAST = (this.contrast !== 1.0);
  37404. defines.EXPOSURE = (this.exposure !== 1.0);
  37405. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37406. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37407. if (defines.COLORGRADING) {
  37408. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37409. }
  37410. else {
  37411. defines.COLORGRADING3D = false;
  37412. }
  37413. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37414. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37415. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37416. defines.GRAIN = this.grainEnabled;
  37417. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37418. };
  37419. /**
  37420. * Returns true if all the image processing information are ready.
  37421. */
  37422. ImageProcessingConfiguration.prototype.isReady = function () {
  37423. // Color Grading texure can not be none blocking.
  37424. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37425. };
  37426. /**
  37427. * Binds the image processing to the shader.
  37428. * @param effect The effect to bind to
  37429. */
  37430. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37431. if (aspectRatio === void 0) { aspectRatio = 1; }
  37432. // Color Curves
  37433. if (this._colorCurvesEnabled && this.colorCurves) {
  37434. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37435. }
  37436. // Vignette
  37437. if (this._vignetteEnabled) {
  37438. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37439. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37440. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37441. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37442. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37443. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37444. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37445. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37446. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37447. var vignettePower = -2.0 * this.vignetteWeight;
  37448. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37449. }
  37450. // Exposure
  37451. effect.setFloat("exposureLinear", this.exposure);
  37452. // Contrast
  37453. effect.setFloat("contrast", this.contrast);
  37454. // Color transform settings
  37455. if (this.colorGradingTexture) {
  37456. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37457. var textureSize = this.colorGradingTexture.getSize().height;
  37458. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37459. 0.5 / textureSize, // textureOffset
  37460. textureSize, // textureSize
  37461. this.colorGradingTexture.level // weight
  37462. );
  37463. }
  37464. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37465. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37466. };
  37467. /**
  37468. * Clones the current image processing instance.
  37469. * @return The cloned image processing
  37470. */
  37471. ImageProcessingConfiguration.prototype.clone = function () {
  37472. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37473. };
  37474. /**
  37475. * Serializes the current image processing instance to a json representation.
  37476. * @return a JSON representation
  37477. */
  37478. ImageProcessingConfiguration.prototype.serialize = function () {
  37479. return BABYLON.SerializationHelper.Serialize(this);
  37480. };
  37481. /**
  37482. * Parses the image processing from a json representation.
  37483. * @param source the JSON source to parse
  37484. * @return The parsed image processing
  37485. */
  37486. ImageProcessingConfiguration.Parse = function (source) {
  37487. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37488. };
  37489. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37490. /**
  37491. * Used to apply the vignette as a mix with the pixel color.
  37492. */
  37493. get: function () {
  37494. return this._VIGNETTEMODE_MULTIPLY;
  37495. },
  37496. enumerable: true,
  37497. configurable: true
  37498. });
  37499. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37500. /**
  37501. * Used to apply the vignette as a replacement of the pixel color.
  37502. */
  37503. get: function () {
  37504. return this._VIGNETTEMODE_OPAQUE;
  37505. },
  37506. enumerable: true,
  37507. configurable: true
  37508. });
  37509. // Static constants associated to the image processing.
  37510. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37511. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37512. __decorate([
  37513. BABYLON.serializeAsColorCurves()
  37514. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37515. __decorate([
  37516. BABYLON.serialize()
  37517. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37518. __decorate([
  37519. BABYLON.serializeAsTexture()
  37520. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37521. __decorate([
  37522. BABYLON.serialize()
  37523. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37524. __decorate([
  37525. BABYLON.serialize()
  37526. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37527. __decorate([
  37528. BABYLON.serialize()
  37529. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37530. __decorate([
  37531. BABYLON.serialize()
  37532. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37533. __decorate([
  37534. BABYLON.serialize()
  37535. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37536. __decorate([
  37537. BABYLON.serialize()
  37538. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37539. __decorate([
  37540. BABYLON.serialize()
  37541. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37542. __decorate([
  37543. BABYLON.serialize()
  37544. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37545. __decorate([
  37546. BABYLON.serialize()
  37547. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37548. __decorate([
  37549. BABYLON.serialize()
  37550. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37551. __decorate([
  37552. BABYLON.serializeAsColor4()
  37553. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37554. __decorate([
  37555. BABYLON.serialize()
  37556. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37557. __decorate([
  37558. BABYLON.serialize()
  37559. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37560. __decorate([
  37561. BABYLON.serialize()
  37562. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37563. __decorate([
  37564. BABYLON.serialize()
  37565. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37566. __decorate([
  37567. BABYLON.serialize()
  37568. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37569. __decorate([
  37570. BABYLON.serialize()
  37571. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37572. __decorate([
  37573. BABYLON.serialize()
  37574. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37575. __decorate([
  37576. BABYLON.serialize()
  37577. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37578. return ImageProcessingConfiguration;
  37579. }());
  37580. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37581. })(BABYLON || (BABYLON = {}));
  37582. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37583. var BABYLON;
  37584. (function (BABYLON) {
  37585. /**
  37586. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37587. * It can help converting any input color in a desired output one. This can then be used to create effects
  37588. * from sepia, black and white to sixties or futuristic rendering...
  37589. *
  37590. * The only supported format is currently 3dl.
  37591. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37592. */
  37593. var ColorGradingTexture = /** @class */ (function (_super) {
  37594. __extends(ColorGradingTexture, _super);
  37595. /**
  37596. * Instantiates a ColorGradingTexture from the following parameters.
  37597. *
  37598. * @param url The location of the color gradind data (currently only supporting 3dl)
  37599. * @param scene The scene the texture will be used in
  37600. */
  37601. function ColorGradingTexture(url, scene) {
  37602. var _this = _super.call(this, scene) || this;
  37603. if (!url) {
  37604. return _this;
  37605. }
  37606. _this._engine = scene.getEngine();
  37607. _this._textureMatrix = BABYLON.Matrix.Identity();
  37608. _this.name = url;
  37609. _this.url = url;
  37610. _this.hasAlpha = false;
  37611. _this.isCube = false;
  37612. _this.is3D = _this._engine.webGLVersion > 1;
  37613. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37614. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37615. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37616. _this.anisotropicFilteringLevel = 1;
  37617. _this._texture = _this._getFromCache(url, true);
  37618. if (!_this._texture) {
  37619. if (!scene.useDelayedTextureLoading) {
  37620. _this.loadTexture();
  37621. }
  37622. else {
  37623. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37624. }
  37625. }
  37626. return _this;
  37627. }
  37628. /**
  37629. * Returns the texture matrix used in most of the material.
  37630. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37631. */
  37632. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37633. return this._textureMatrix;
  37634. };
  37635. /**
  37636. * Occurs when the file being loaded is a .3dl LUT file.
  37637. */
  37638. ColorGradingTexture.prototype.load3dlTexture = function () {
  37639. var engine = this._engine;
  37640. var texture;
  37641. if (engine.webGLVersion === 1) {
  37642. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37643. }
  37644. else {
  37645. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37646. }
  37647. this._texture = texture;
  37648. var callback = function (text) {
  37649. if (typeof text !== "string") {
  37650. return;
  37651. }
  37652. var data = null;
  37653. var tempData = null;
  37654. var line;
  37655. var lines = text.split('\n');
  37656. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37657. var maxColor = 0;
  37658. for (var i = 0; i < lines.length; i++) {
  37659. line = lines[i];
  37660. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37661. continue;
  37662. if (line.indexOf('#') === 0)
  37663. continue;
  37664. var words = line.split(" ");
  37665. if (size === 0) {
  37666. // Number of space + one
  37667. size = words.length;
  37668. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37669. tempData = new Float32Array(size * size * size * 4);
  37670. continue;
  37671. }
  37672. if (size != 0) {
  37673. var r = Math.max(parseInt(words[0]), 0);
  37674. var g = Math.max(parseInt(words[1]), 0);
  37675. var b = Math.max(parseInt(words[2]), 0);
  37676. maxColor = Math.max(r, maxColor);
  37677. maxColor = Math.max(g, maxColor);
  37678. maxColor = Math.max(b, maxColor);
  37679. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37680. if (tempData) {
  37681. tempData[pixelStorageIndex + 0] = r;
  37682. tempData[pixelStorageIndex + 1] = g;
  37683. tempData[pixelStorageIndex + 2] = b;
  37684. }
  37685. pixelIndexSlice++;
  37686. if (pixelIndexSlice % size == 0) {
  37687. pixelIndexH++;
  37688. pixelIndexSlice = 0;
  37689. if (pixelIndexH % size == 0) {
  37690. pixelIndexW++;
  37691. pixelIndexH = 0;
  37692. }
  37693. }
  37694. }
  37695. }
  37696. if (tempData && data) {
  37697. for (var i = 0; i < tempData.length; i++) {
  37698. if (i > 0 && (i + 1) % 4 === 0) {
  37699. data[i] = 255;
  37700. }
  37701. else {
  37702. var value = tempData[i];
  37703. data[i] = (value / maxColor * 255);
  37704. }
  37705. }
  37706. }
  37707. if (texture.is3D) {
  37708. texture.updateSize(size, size, size);
  37709. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37710. }
  37711. else {
  37712. texture.updateSize(size * size, size);
  37713. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37714. }
  37715. };
  37716. var scene = this.getScene();
  37717. if (scene) {
  37718. scene._loadFile(this.url, callback);
  37719. }
  37720. else {
  37721. this._engine._loadFile(this.url, callback);
  37722. }
  37723. return this._texture;
  37724. };
  37725. /**
  37726. * Starts the loading process of the texture.
  37727. */
  37728. ColorGradingTexture.prototype.loadTexture = function () {
  37729. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37730. this.load3dlTexture();
  37731. }
  37732. };
  37733. /**
  37734. * Clones the color gradind texture.
  37735. */
  37736. ColorGradingTexture.prototype.clone = function () {
  37737. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37738. // Base texture
  37739. newTexture.level = this.level;
  37740. return newTexture;
  37741. };
  37742. /**
  37743. * Called during delayed load for textures.
  37744. */
  37745. ColorGradingTexture.prototype.delayLoad = function () {
  37746. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37747. return;
  37748. }
  37749. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37750. this._texture = this._getFromCache(this.url, true);
  37751. if (!this._texture) {
  37752. this.loadTexture();
  37753. }
  37754. };
  37755. /**
  37756. * Parses a color grading texture serialized by Babylon.
  37757. * @param parsedTexture The texture information being parsedTexture
  37758. * @param scene The scene to load the texture in
  37759. * @param rootUrl The root url of the data assets to load
  37760. * @return A color gradind texture
  37761. */
  37762. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37763. var texture = null;
  37764. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37765. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37766. texture.name = parsedTexture.name;
  37767. texture.level = parsedTexture.level;
  37768. }
  37769. return texture;
  37770. };
  37771. /**
  37772. * Serializes the LUT texture to json format.
  37773. */
  37774. ColorGradingTexture.prototype.serialize = function () {
  37775. if (!this.name) {
  37776. return null;
  37777. }
  37778. var serializationObject = {};
  37779. serializationObject.name = this.name;
  37780. serializationObject.level = this.level;
  37781. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37782. return serializationObject;
  37783. };
  37784. /**
  37785. * Empty line regex stored for GC.
  37786. */
  37787. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37788. return ColorGradingTexture;
  37789. }(BABYLON.BaseTexture));
  37790. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37791. })(BABYLON || (BABYLON = {}));
  37792. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37793. var BABYLON;
  37794. (function (BABYLON) {
  37795. /**
  37796. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37797. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37798. * 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;
  37799. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37800. */
  37801. var ColorCurves = /** @class */ (function () {
  37802. function ColorCurves() {
  37803. this._dirty = true;
  37804. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37805. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37806. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37807. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37808. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37809. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37810. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37811. this._globalHue = 30;
  37812. this._globalDensity = 0;
  37813. this._globalSaturation = 0;
  37814. this._globalExposure = 0;
  37815. this._highlightsHue = 30;
  37816. this._highlightsDensity = 0;
  37817. this._highlightsSaturation = 0;
  37818. this._highlightsExposure = 0;
  37819. this._midtonesHue = 30;
  37820. this._midtonesDensity = 0;
  37821. this._midtonesSaturation = 0;
  37822. this._midtonesExposure = 0;
  37823. this._shadowsHue = 30;
  37824. this._shadowsDensity = 0;
  37825. this._shadowsSaturation = 0;
  37826. this._shadowsExposure = 0;
  37827. }
  37828. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37829. /**
  37830. * Gets the global Hue value.
  37831. * 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).
  37832. */
  37833. get: function () {
  37834. return this._globalHue;
  37835. },
  37836. /**
  37837. * Sets the global Hue value.
  37838. * 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).
  37839. */
  37840. set: function (value) {
  37841. this._globalHue = value;
  37842. this._dirty = true;
  37843. },
  37844. enumerable: true,
  37845. configurable: true
  37846. });
  37847. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37848. /**
  37849. * Gets the global Density value.
  37850. * 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.
  37851. * Values less than zero provide a filter of opposite hue.
  37852. */
  37853. get: function () {
  37854. return this._globalDensity;
  37855. },
  37856. /**
  37857. * Sets the global Density value.
  37858. * 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.
  37859. * Values less than zero provide a filter of opposite hue.
  37860. */
  37861. set: function (value) {
  37862. this._globalDensity = value;
  37863. this._dirty = true;
  37864. },
  37865. enumerable: true,
  37866. configurable: true
  37867. });
  37868. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37869. /**
  37870. * Gets the global Saturation value.
  37871. * 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.
  37872. */
  37873. get: function () {
  37874. return this._globalSaturation;
  37875. },
  37876. /**
  37877. * Sets the global Saturation value.
  37878. * 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.
  37879. */
  37880. set: function (value) {
  37881. this._globalSaturation = value;
  37882. this._dirty = true;
  37883. },
  37884. enumerable: true,
  37885. configurable: true
  37886. });
  37887. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37888. /**
  37889. * Gets the highlights Hue value.
  37890. * 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).
  37891. */
  37892. get: function () {
  37893. return this._highlightsHue;
  37894. },
  37895. /**
  37896. * Sets the highlights Hue value.
  37897. * 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).
  37898. */
  37899. set: function (value) {
  37900. this._highlightsHue = value;
  37901. this._dirty = true;
  37902. },
  37903. enumerable: true,
  37904. configurable: true
  37905. });
  37906. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37907. /**
  37908. * Gets the highlights Density value.
  37909. * 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.
  37910. * Values less than zero provide a filter of opposite hue.
  37911. */
  37912. get: function () {
  37913. return this._highlightsDensity;
  37914. },
  37915. /**
  37916. * Sets the highlights Density value.
  37917. * 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.
  37918. * Values less than zero provide a filter of opposite hue.
  37919. */
  37920. set: function (value) {
  37921. this._highlightsDensity = value;
  37922. this._dirty = true;
  37923. },
  37924. enumerable: true,
  37925. configurable: true
  37926. });
  37927. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37928. /**
  37929. * Gets the highlights Saturation value.
  37930. * 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.
  37931. */
  37932. get: function () {
  37933. return this._highlightsSaturation;
  37934. },
  37935. /**
  37936. * Sets the highlights Saturation value.
  37937. * 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.
  37938. */
  37939. set: function (value) {
  37940. this._highlightsSaturation = value;
  37941. this._dirty = true;
  37942. },
  37943. enumerable: true,
  37944. configurable: true
  37945. });
  37946. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37947. /**
  37948. * Gets the highlights Exposure value.
  37949. * 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.
  37950. */
  37951. get: function () {
  37952. return this._highlightsExposure;
  37953. },
  37954. /**
  37955. * Sets the highlights Exposure value.
  37956. * 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.
  37957. */
  37958. set: function (value) {
  37959. this._highlightsExposure = value;
  37960. this._dirty = true;
  37961. },
  37962. enumerable: true,
  37963. configurable: true
  37964. });
  37965. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37966. /**
  37967. * Gets the midtones Hue value.
  37968. * 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).
  37969. */
  37970. get: function () {
  37971. return this._midtonesHue;
  37972. },
  37973. /**
  37974. * Sets the midtones Hue value.
  37975. * 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).
  37976. */
  37977. set: function (value) {
  37978. this._midtonesHue = value;
  37979. this._dirty = true;
  37980. },
  37981. enumerable: true,
  37982. configurable: true
  37983. });
  37984. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37985. /**
  37986. * Gets the midtones Density value.
  37987. * 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.
  37988. * Values less than zero provide a filter of opposite hue.
  37989. */
  37990. get: function () {
  37991. return this._midtonesDensity;
  37992. },
  37993. /**
  37994. * Sets the midtones Density value.
  37995. * 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.
  37996. * Values less than zero provide a filter of opposite hue.
  37997. */
  37998. set: function (value) {
  37999. this._midtonesDensity = value;
  38000. this._dirty = true;
  38001. },
  38002. enumerable: true,
  38003. configurable: true
  38004. });
  38005. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38006. /**
  38007. * Gets the midtones Saturation value.
  38008. * 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.
  38009. */
  38010. get: function () {
  38011. return this._midtonesSaturation;
  38012. },
  38013. /**
  38014. * Sets the midtones Saturation value.
  38015. * 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.
  38016. */
  38017. set: function (value) {
  38018. this._midtonesSaturation = value;
  38019. this._dirty = true;
  38020. },
  38021. enumerable: true,
  38022. configurable: true
  38023. });
  38024. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38025. /**
  38026. * Gets the midtones Exposure value.
  38027. * 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.
  38028. */
  38029. get: function () {
  38030. return this._midtonesExposure;
  38031. },
  38032. /**
  38033. * Sets the midtones Exposure value.
  38034. * 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.
  38035. */
  38036. set: function (value) {
  38037. this._midtonesExposure = value;
  38038. this._dirty = true;
  38039. },
  38040. enumerable: true,
  38041. configurable: true
  38042. });
  38043. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38044. /**
  38045. * Gets the shadows Hue value.
  38046. * 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).
  38047. */
  38048. get: function () {
  38049. return this._shadowsHue;
  38050. },
  38051. /**
  38052. * Sets the shadows Hue value.
  38053. * 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).
  38054. */
  38055. set: function (value) {
  38056. this._shadowsHue = value;
  38057. this._dirty = true;
  38058. },
  38059. enumerable: true,
  38060. configurable: true
  38061. });
  38062. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38063. /**
  38064. * Gets the shadows Density value.
  38065. * 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.
  38066. * Values less than zero provide a filter of opposite hue.
  38067. */
  38068. get: function () {
  38069. return this._shadowsDensity;
  38070. },
  38071. /**
  38072. * Sets the shadows Density value.
  38073. * 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.
  38074. * Values less than zero provide a filter of opposite hue.
  38075. */
  38076. set: function (value) {
  38077. this._shadowsDensity = value;
  38078. this._dirty = true;
  38079. },
  38080. enumerable: true,
  38081. configurable: true
  38082. });
  38083. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38084. /**
  38085. * Gets the shadows Saturation value.
  38086. * 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.
  38087. */
  38088. get: function () {
  38089. return this._shadowsSaturation;
  38090. },
  38091. /**
  38092. * Sets the shadows Saturation value.
  38093. * 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.
  38094. */
  38095. set: function (value) {
  38096. this._shadowsSaturation = value;
  38097. this._dirty = true;
  38098. },
  38099. enumerable: true,
  38100. configurable: true
  38101. });
  38102. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38103. /**
  38104. * Gets the shadows Exposure value.
  38105. * 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.
  38106. */
  38107. get: function () {
  38108. return this._shadowsExposure;
  38109. },
  38110. /**
  38111. * Sets the shadows Exposure value.
  38112. * 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.
  38113. */
  38114. set: function (value) {
  38115. this._shadowsExposure = value;
  38116. this._dirty = true;
  38117. },
  38118. enumerable: true,
  38119. configurable: true
  38120. });
  38121. ColorCurves.prototype.getClassName = function () {
  38122. return "ColorCurves";
  38123. };
  38124. /**
  38125. * Binds the color curves to the shader.
  38126. * @param colorCurves The color curve to bind
  38127. * @param effect The effect to bind to
  38128. */
  38129. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38130. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38131. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38132. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38133. if (colorCurves._dirty) {
  38134. colorCurves._dirty = false;
  38135. // Fill in global info.
  38136. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38137. // Compute highlights info.
  38138. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38139. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38140. // Compute midtones info.
  38141. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38142. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38143. // Compute shadows info.
  38144. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38145. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38146. // Compute deltas (neutral is midtones).
  38147. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38148. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38149. }
  38150. if (effect) {
  38151. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38152. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38153. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38154. }
  38155. };
  38156. /**
  38157. * Prepare the list of uniforms associated with the ColorCurves effects.
  38158. * @param uniformsList The list of uniforms used in the effect
  38159. */
  38160. ColorCurves.PrepareUniforms = function (uniformsList) {
  38161. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38162. };
  38163. /**
  38164. * Returns color grading data based on a hue, density, saturation and exposure value.
  38165. * @param filterHue The hue of the color filter.
  38166. * @param filterDensity The density of the color filter.
  38167. * @param saturation The saturation.
  38168. * @param exposure The exposure.
  38169. * @param result The result data container.
  38170. */
  38171. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38172. if (hue == null) {
  38173. return;
  38174. }
  38175. hue = ColorCurves.clamp(hue, 0, 360);
  38176. density = ColorCurves.clamp(density, -100, 100);
  38177. saturation = ColorCurves.clamp(saturation, -100, 100);
  38178. exposure = ColorCurves.clamp(exposure, -100, 100);
  38179. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38180. // so that the maximum filter density is only 50% control. This provides fine control
  38181. // for small values and reasonable range.
  38182. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38183. density *= 0.5;
  38184. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38185. if (density < 0) {
  38186. density *= -1;
  38187. hue = (hue + 180) % 360;
  38188. }
  38189. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38190. result.scaleToRef(2, result);
  38191. result.a = 1 + 0.01 * saturation;
  38192. };
  38193. /**
  38194. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38195. * @param value The input slider value in range [-100,100].
  38196. * @returns Adjusted value.
  38197. */
  38198. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38199. value /= 100;
  38200. var x = Math.abs(value);
  38201. x = Math.pow(x, 2);
  38202. if (value < 0) {
  38203. x *= -1;
  38204. }
  38205. x *= 100;
  38206. return x;
  38207. };
  38208. /**
  38209. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38210. * @param hue The hue (H) input.
  38211. * @param saturation The saturation (S) input.
  38212. * @param brightness The brightness (B) input.
  38213. * @result An RGBA color represented as Vector4.
  38214. */
  38215. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38216. var h = ColorCurves.clamp(hue, 0, 360);
  38217. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38218. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38219. if (s === 0) {
  38220. result.r = v;
  38221. result.g = v;
  38222. result.b = v;
  38223. }
  38224. else {
  38225. // sector 0 to 5
  38226. h /= 60;
  38227. var i = Math.floor(h);
  38228. // fractional part of h
  38229. var f = h - i;
  38230. var p = v * (1 - s);
  38231. var q = v * (1 - s * f);
  38232. var t = v * (1 - s * (1 - f));
  38233. switch (i) {
  38234. case 0:
  38235. result.r = v;
  38236. result.g = t;
  38237. result.b = p;
  38238. break;
  38239. case 1:
  38240. result.r = q;
  38241. result.g = v;
  38242. result.b = p;
  38243. break;
  38244. case 2:
  38245. result.r = p;
  38246. result.g = v;
  38247. result.b = t;
  38248. break;
  38249. case 3:
  38250. result.r = p;
  38251. result.g = q;
  38252. result.b = v;
  38253. break;
  38254. case 4:
  38255. result.r = t;
  38256. result.g = p;
  38257. result.b = v;
  38258. break;
  38259. default:// case 5:
  38260. result.r = v;
  38261. result.g = p;
  38262. result.b = q;
  38263. break;
  38264. }
  38265. }
  38266. result.a = 1;
  38267. };
  38268. /**
  38269. * Returns a value clamped between min and max
  38270. * @param value The value to clamp
  38271. * @param min The minimum of value
  38272. * @param max The maximum of value
  38273. * @returns The clamped value.
  38274. */
  38275. ColorCurves.clamp = function (value, min, max) {
  38276. return Math.min(Math.max(value, min), max);
  38277. };
  38278. /**
  38279. * Clones the current color curve instance.
  38280. * @return The cloned curves
  38281. */
  38282. ColorCurves.prototype.clone = function () {
  38283. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38284. };
  38285. /**
  38286. * Serializes the current color curve instance to a json representation.
  38287. * @return a JSON representation
  38288. */
  38289. ColorCurves.prototype.serialize = function () {
  38290. return BABYLON.SerializationHelper.Serialize(this);
  38291. };
  38292. /**
  38293. * Parses the color curve from a json representation.
  38294. * @param source the JSON source to parse
  38295. * @return The parsed curves
  38296. */
  38297. ColorCurves.Parse = function (source) {
  38298. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38299. };
  38300. __decorate([
  38301. BABYLON.serialize()
  38302. ], ColorCurves.prototype, "_globalHue", void 0);
  38303. __decorate([
  38304. BABYLON.serialize()
  38305. ], ColorCurves.prototype, "_globalDensity", void 0);
  38306. __decorate([
  38307. BABYLON.serialize()
  38308. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38309. __decorate([
  38310. BABYLON.serialize()
  38311. ], ColorCurves.prototype, "_globalExposure", void 0);
  38312. __decorate([
  38313. BABYLON.serialize()
  38314. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38315. __decorate([
  38316. BABYLON.serialize()
  38317. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38318. __decorate([
  38319. BABYLON.serialize()
  38320. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38321. __decorate([
  38322. BABYLON.serialize()
  38323. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38324. __decorate([
  38325. BABYLON.serialize()
  38326. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38327. __decorate([
  38328. BABYLON.serialize()
  38329. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38330. __decorate([
  38331. BABYLON.serialize()
  38332. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38333. __decorate([
  38334. BABYLON.serialize()
  38335. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38336. return ColorCurves;
  38337. }());
  38338. BABYLON.ColorCurves = ColorCurves;
  38339. })(BABYLON || (BABYLON = {}));
  38340. //# sourceMappingURL=babylon.colorCurves.js.map
  38341. //# sourceMappingURL=babylon.behavior.js.map
  38342. var BABYLON;
  38343. (function (BABYLON) {
  38344. /**
  38345. * "Static Class" containing the most commonly used helper while dealing with material for
  38346. * rendering purpose.
  38347. *
  38348. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38349. *
  38350. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38351. */
  38352. var MaterialHelper = /** @class */ (function () {
  38353. function MaterialHelper() {
  38354. }
  38355. /**
  38356. * Bind the current view position to an effect.
  38357. * @param effect The effect to be bound
  38358. * @param scene The scene the eyes position is used from
  38359. */
  38360. MaterialHelper.BindEyePosition = function (effect, scene) {
  38361. if (scene._forcedViewPosition) {
  38362. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38363. return;
  38364. }
  38365. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38366. };
  38367. /**
  38368. * Helps preparing the defines values about the UVs in used in the effect.
  38369. * UVs are shared as much as we can accross chanels in the shaders.
  38370. * @param texture The texture we are preparing the UVs for
  38371. * @param defines The defines to update
  38372. * @param key The chanel key "diffuse", "specular"... used in the shader
  38373. */
  38374. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38375. defines._needUVs = true;
  38376. defines[key] = true;
  38377. if (texture.getTextureMatrix().isIdentity(true)) {
  38378. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38379. if (texture.coordinatesIndex === 0) {
  38380. defines["MAINUV1"] = true;
  38381. }
  38382. else {
  38383. defines["MAINUV2"] = true;
  38384. }
  38385. }
  38386. else {
  38387. defines[key + "DIRECTUV"] = 0;
  38388. }
  38389. };
  38390. /**
  38391. * Binds a texture matrix value to its corrsponding uniform
  38392. * @param texture The texture to bind the matrix for
  38393. * @param uniformBuffer The uniform buffer receivin the data
  38394. * @param key The chanel key "diffuse", "specular"... used in the shader
  38395. */
  38396. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38397. var matrix = texture.getTextureMatrix();
  38398. if (!matrix.isIdentity(true)) {
  38399. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38400. }
  38401. };
  38402. /**
  38403. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38404. * @param mesh defines the current mesh
  38405. * @param scene defines the current scene
  38406. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38407. * @param pointsCloud defines if point cloud rendering has to be turned on
  38408. * @param fogEnabled defines if fog has to be turned on
  38409. * @param alphaTest defines if alpha testing has to be turned on
  38410. * @param defines defines the current list of defines
  38411. */
  38412. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38413. if (defines._areMiscDirty) {
  38414. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38415. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38416. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38417. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38418. defines["ALPHATEST"] = alphaTest;
  38419. }
  38420. };
  38421. /**
  38422. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38423. * @param scene defines the current scene
  38424. * @param engine defines the current engine
  38425. * @param defines specifies the list of active defines
  38426. * @param useInstances defines if instances have to be turned on
  38427. * @param useClipPlane defines if clip plane have to be turned on
  38428. */
  38429. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38430. if (useClipPlane === void 0) { useClipPlane = null; }
  38431. var changed = false;
  38432. if (useClipPlane == null) {
  38433. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38434. }
  38435. if (defines["CLIPPLANE"] !== useClipPlane) {
  38436. defines["CLIPPLANE"] = useClipPlane;
  38437. changed = true;
  38438. }
  38439. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38440. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38441. changed = true;
  38442. }
  38443. if (defines["INSTANCES"] !== useInstances) {
  38444. defines["INSTANCES"] = useInstances;
  38445. changed = true;
  38446. }
  38447. if (changed) {
  38448. defines.markAsUnprocessed();
  38449. }
  38450. };
  38451. /**
  38452. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38453. * @param mesh The mesh containing the geometry data we will draw
  38454. * @param defines The defines to update
  38455. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38456. * @param useBones Precise whether bones should be used or not (override mesh info)
  38457. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38458. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38459. * @returns false if defines are considered not dirty and have not been checked
  38460. */
  38461. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38462. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38463. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38464. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38465. return false;
  38466. }
  38467. defines._normals = defines._needNormals;
  38468. defines._uvs = defines._needUVs;
  38469. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38470. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38471. defines["TANGENT"] = true;
  38472. }
  38473. if (defines._needUVs) {
  38474. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38475. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38476. }
  38477. else {
  38478. defines["UV1"] = false;
  38479. defines["UV2"] = false;
  38480. }
  38481. if (useVertexColor) {
  38482. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38483. defines["VERTEXCOLOR"] = hasVertexColors;
  38484. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38485. }
  38486. if (useBones) {
  38487. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38488. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38489. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38490. }
  38491. else {
  38492. defines["NUM_BONE_INFLUENCERS"] = 0;
  38493. defines["BonesPerMesh"] = 0;
  38494. }
  38495. }
  38496. if (useMorphTargets) {
  38497. var manager = mesh.morphTargetManager;
  38498. if (manager) {
  38499. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38500. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38501. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38502. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38503. }
  38504. else {
  38505. defines["MORPHTARGETS_TANGENT"] = false;
  38506. defines["MORPHTARGETS_NORMAL"] = false;
  38507. defines["MORPHTARGETS"] = false;
  38508. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38509. }
  38510. }
  38511. return true;
  38512. };
  38513. /**
  38514. * Prepares the defines related to the light information passed in parameter
  38515. * @param scene The scene we are intending to draw
  38516. * @param mesh The mesh the effect is compiling for
  38517. * @param defines The defines to update
  38518. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38519. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38520. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38521. * @returns true if normals will be required for the rest of the effect
  38522. */
  38523. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38524. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38525. if (disableLighting === void 0) { disableLighting = false; }
  38526. if (!defines._areLightsDirty) {
  38527. return defines._needNormals;
  38528. }
  38529. var lightIndex = 0;
  38530. var needNormals = false;
  38531. var needRebuild = false;
  38532. var lightmapMode = false;
  38533. var shadowEnabled = false;
  38534. var specularEnabled = false;
  38535. if (scene.lightsEnabled && !disableLighting) {
  38536. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38537. var light = _a[_i];
  38538. needNormals = true;
  38539. if (defines["LIGHT" + lightIndex] === undefined) {
  38540. needRebuild = true;
  38541. }
  38542. defines["LIGHT" + lightIndex] = true;
  38543. defines["SPOTLIGHT" + lightIndex] = false;
  38544. defines["HEMILIGHT" + lightIndex] = false;
  38545. defines["POINTLIGHT" + lightIndex] = false;
  38546. defines["DIRLIGHT" + lightIndex] = false;
  38547. var type;
  38548. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38549. type = "SPOTLIGHT" + lightIndex;
  38550. var spotLight = light;
  38551. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38552. }
  38553. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38554. type = "HEMILIGHT" + lightIndex;
  38555. }
  38556. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38557. type = "POINTLIGHT" + lightIndex;
  38558. }
  38559. else {
  38560. type = "DIRLIGHT" + lightIndex;
  38561. }
  38562. defines[type] = true;
  38563. // Specular
  38564. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38565. specularEnabled = true;
  38566. }
  38567. // Shadows
  38568. defines["SHADOW" + lightIndex] = false;
  38569. defines["SHADOWPCF" + lightIndex] = false;
  38570. defines["SHADOWESM" + lightIndex] = false;
  38571. defines["SHADOWCUBE" + lightIndex] = false;
  38572. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38573. var shadowGenerator = light.getShadowGenerator();
  38574. if (shadowGenerator) {
  38575. shadowEnabled = true;
  38576. shadowGenerator.prepareDefines(defines, lightIndex);
  38577. }
  38578. }
  38579. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38580. lightmapMode = true;
  38581. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38582. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38583. }
  38584. else {
  38585. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38586. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38587. }
  38588. lightIndex++;
  38589. if (lightIndex === maxSimultaneousLights)
  38590. break;
  38591. }
  38592. }
  38593. defines["SPECULARTERM"] = specularEnabled;
  38594. defines["SHADOWS"] = shadowEnabled;
  38595. // Resetting all other lights if any
  38596. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38597. if (defines["LIGHT" + index] !== undefined) {
  38598. defines["LIGHT" + index] = false;
  38599. defines["HEMILIGHT" + lightIndex] = false;
  38600. defines["POINTLIGHT" + lightIndex] = false;
  38601. defines["DIRLIGHT" + lightIndex] = false;
  38602. defines["SPOTLIGHT" + lightIndex] = false;
  38603. defines["SHADOW" + lightIndex] = false;
  38604. }
  38605. }
  38606. var caps = scene.getEngine().getCaps();
  38607. if (defines["SHADOWFLOAT"] === undefined) {
  38608. needRebuild = true;
  38609. }
  38610. defines["SHADOWFLOAT"] = shadowEnabled &&
  38611. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38612. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38613. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38614. if (needRebuild) {
  38615. defines.rebuild();
  38616. }
  38617. return needNormals;
  38618. };
  38619. /**
  38620. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38621. * that won t be acctive due to defines being turned off.
  38622. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38623. * @param samplersList The samplers list
  38624. * @param defines The defines helping in the list generation
  38625. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38626. */
  38627. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38628. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38629. var uniformsList;
  38630. var uniformBuffersList = null;
  38631. if (uniformsListOrOptions.uniformsNames) {
  38632. var options = uniformsListOrOptions;
  38633. uniformsList = options.uniformsNames;
  38634. uniformBuffersList = options.uniformBuffersNames;
  38635. samplersList = options.samplers;
  38636. defines = options.defines;
  38637. maxSimultaneousLights = options.maxSimultaneousLights;
  38638. }
  38639. else {
  38640. uniformsList = uniformsListOrOptions;
  38641. if (!samplersList) {
  38642. samplersList = [];
  38643. }
  38644. }
  38645. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38646. if (!defines["LIGHT" + lightIndex]) {
  38647. break;
  38648. }
  38649. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38650. if (uniformBuffersList) {
  38651. uniformBuffersList.push("Light" + lightIndex);
  38652. }
  38653. samplersList.push("shadowSampler" + lightIndex);
  38654. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38655. samplersList.push("projectionLightSampler" + lightIndex);
  38656. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38657. }
  38658. }
  38659. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38660. uniformsList.push("morphTargetInfluences");
  38661. }
  38662. };
  38663. /**
  38664. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38665. * @param defines The defines to update while falling back
  38666. * @param fallbacks The authorized effect fallbacks
  38667. * @param maxSimultaneousLights The maximum number of lights allowed
  38668. * @param rank the current rank of the Effect
  38669. * @returns The newly affected rank
  38670. */
  38671. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38672. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38673. if (rank === void 0) { rank = 0; }
  38674. var lightFallbackRank = 0;
  38675. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38676. if (!defines["LIGHT" + lightIndex]) {
  38677. break;
  38678. }
  38679. if (lightIndex > 0) {
  38680. lightFallbackRank = rank + lightIndex;
  38681. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38682. }
  38683. if (!defines["SHADOWS"]) {
  38684. if (defines["SHADOW" + lightIndex]) {
  38685. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38686. }
  38687. if (defines["SHADOWPCF" + lightIndex]) {
  38688. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38689. }
  38690. if (defines["SHADOWESM" + lightIndex]) {
  38691. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38692. }
  38693. }
  38694. }
  38695. return lightFallbackRank++;
  38696. };
  38697. /**
  38698. * Prepares the list of attributes required for morph targets according to the effect defines.
  38699. * @param attribs The current list of supported attribs
  38700. * @param mesh The mesh to prepare the morph targets attributes for
  38701. * @param defines The current Defines of the effect
  38702. */
  38703. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38704. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38705. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38706. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38707. var manager = mesh.morphTargetManager;
  38708. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38709. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38710. for (var index = 0; index < influencers; index++) {
  38711. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38712. if (normal) {
  38713. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38714. }
  38715. if (tangent) {
  38716. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38717. }
  38718. if (attribs.length > maxAttributesCount) {
  38719. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38720. }
  38721. }
  38722. }
  38723. };
  38724. /**
  38725. * Prepares the list of attributes required for bones according to the effect defines.
  38726. * @param attribs The current list of supported attribs
  38727. * @param mesh The mesh to prepare the bones attributes for
  38728. * @param defines The current Defines of the effect
  38729. * @param fallbacks The current efffect fallback strategy
  38730. */
  38731. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38732. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38733. fallbacks.addCPUSkinningFallback(0, mesh);
  38734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38736. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38739. }
  38740. }
  38741. };
  38742. /**
  38743. * Prepares the list of attributes required for instances according to the effect defines.
  38744. * @param attribs The current list of supported attribs
  38745. * @param defines The current Defines of the effect
  38746. */
  38747. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38748. if (defines["INSTANCES"]) {
  38749. attribs.push("world0");
  38750. attribs.push("world1");
  38751. attribs.push("world2");
  38752. attribs.push("world3");
  38753. }
  38754. };
  38755. /**
  38756. * Binds the light shadow information to the effect for the given mesh.
  38757. * @param light The light containing the generator
  38758. * @param scene The scene the lights belongs to
  38759. * @param mesh The mesh we are binding the information to render
  38760. * @param lightIndex The light index in the effect used to render the mesh
  38761. * @param effect The effect we are binding the data to
  38762. */
  38763. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38764. if (light.shadowEnabled && mesh.receiveShadows) {
  38765. var shadowGenerator = light.getShadowGenerator();
  38766. if (shadowGenerator) {
  38767. shadowGenerator.bindShadowLight(lightIndex, effect);
  38768. }
  38769. }
  38770. };
  38771. /**
  38772. * Binds the light information to the effect.
  38773. * @param light The light containing the generator
  38774. * @param effect The effect we are binding the data to
  38775. * @param lightIndex The light index in the effect used to render
  38776. */
  38777. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38778. light.transferToEffect(effect, lightIndex + "");
  38779. };
  38780. /**
  38781. * Binds the lights information from the scene to the effect for the given mesh.
  38782. * @param scene The scene the lights belongs to
  38783. * @param mesh The mesh we are binding the information to render
  38784. * @param effect The effect we are binding the data to
  38785. * @param defines The generated defines for the effect
  38786. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38787. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38788. */
  38789. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38790. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38791. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38792. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38793. for (var i = 0; i < len; i++) {
  38794. var light = mesh._lightSources[i];
  38795. var iAsString = i.toString();
  38796. var scaledIntensity = light.getScaledIntensity();
  38797. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38798. MaterialHelper.BindLightProperties(light, effect, i);
  38799. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38800. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38801. if (defines["SPECULARTERM"]) {
  38802. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38803. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38804. }
  38805. // Shadows
  38806. if (scene.shadowsEnabled) {
  38807. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38808. }
  38809. light._uniformBuffer.update();
  38810. }
  38811. };
  38812. /**
  38813. * Binds the fog information from the scene to the effect for the given mesh.
  38814. * @param scene The scene the lights belongs to
  38815. * @param mesh The mesh we are binding the information to render
  38816. * @param effect The effect we are binding the data to
  38817. */
  38818. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38819. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38820. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38821. effect.setColor3("vFogColor", scene.fogColor);
  38822. }
  38823. };
  38824. /**
  38825. * Binds the bones information from the mesh to the effect.
  38826. * @param mesh The mesh we are binding the information to render
  38827. * @param effect The effect we are binding the data to
  38828. */
  38829. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38830. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38831. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38832. if (matrices && effect) {
  38833. effect.setMatrices("mBones", matrices);
  38834. }
  38835. }
  38836. };
  38837. /**
  38838. * Binds the morph targets information from the mesh to the effect.
  38839. * @param abstractMesh The mesh we are binding the information to render
  38840. * @param effect The effect we are binding the data to
  38841. */
  38842. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38843. var manager = abstractMesh.morphTargetManager;
  38844. if (!abstractMesh || !manager) {
  38845. return;
  38846. }
  38847. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38848. };
  38849. /**
  38850. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38851. * @param defines The generated defines used in the effect
  38852. * @param effect The effect we are binding the data to
  38853. * @param scene The scene we are willing to render with logarithmic scale for
  38854. */
  38855. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38856. if (defines["LOGARITHMICDEPTH"]) {
  38857. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38858. }
  38859. };
  38860. /**
  38861. * Binds the clip plane information from the scene to the effect.
  38862. * @param scene The scene the clip plane information are extracted from
  38863. * @param effect The effect we are binding the data to
  38864. */
  38865. MaterialHelper.BindClipPlane = function (effect, scene) {
  38866. if (scene.clipPlane) {
  38867. var clipPlane = scene.clipPlane;
  38868. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38869. }
  38870. };
  38871. return MaterialHelper;
  38872. }());
  38873. BABYLON.MaterialHelper = MaterialHelper;
  38874. })(BABYLON || (BABYLON = {}));
  38875. //# sourceMappingURL=babylon.materialHelper.js.map
  38876. var BABYLON;
  38877. (function (BABYLON) {
  38878. var PushMaterial = /** @class */ (function (_super) {
  38879. __extends(PushMaterial, _super);
  38880. function PushMaterial(name, scene) {
  38881. var _this = _super.call(this, name, scene) || this;
  38882. _this._normalMatrix = new BABYLON.Matrix();
  38883. _this.storeEffectOnSubMeshes = true;
  38884. return _this;
  38885. }
  38886. PushMaterial.prototype.getEffect = function () {
  38887. return this._activeEffect;
  38888. };
  38889. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38890. if (!mesh) {
  38891. return false;
  38892. }
  38893. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38894. return true;
  38895. }
  38896. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38897. };
  38898. /**
  38899. * Binds the given world matrix to the active effect
  38900. *
  38901. * @param world the matrix to bind
  38902. */
  38903. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38904. this._activeEffect.setMatrix("world", world);
  38905. };
  38906. /**
  38907. * Binds the given normal matrix to the active effect
  38908. *
  38909. * @param normalMatrix the matrix to bind
  38910. */
  38911. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38912. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38913. };
  38914. PushMaterial.prototype.bind = function (world, mesh) {
  38915. if (!mesh) {
  38916. return;
  38917. }
  38918. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38919. };
  38920. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38921. if (effect === void 0) { effect = null; }
  38922. _super.prototype._afterBind.call(this, mesh);
  38923. this.getScene()._cachedEffect = effect;
  38924. };
  38925. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38926. if (visibility === void 0) { visibility = 1; }
  38927. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38928. };
  38929. return PushMaterial;
  38930. }(BABYLON.Material));
  38931. BABYLON.PushMaterial = PushMaterial;
  38932. })(BABYLON || (BABYLON = {}));
  38933. //# sourceMappingURL=babylon.pushMaterial.js.map
  38934. var BABYLON;
  38935. (function (BABYLON) {
  38936. /** @ignore */
  38937. var StandardMaterialDefines = /** @class */ (function (_super) {
  38938. __extends(StandardMaterialDefines, _super);
  38939. function StandardMaterialDefines() {
  38940. var _this = _super.call(this) || this;
  38941. _this.MAINUV1 = false;
  38942. _this.MAINUV2 = false;
  38943. _this.DIFFUSE = false;
  38944. _this.DIFFUSEDIRECTUV = 0;
  38945. _this.AMBIENT = false;
  38946. _this.AMBIENTDIRECTUV = 0;
  38947. _this.OPACITY = false;
  38948. _this.OPACITYDIRECTUV = 0;
  38949. _this.OPACITYRGB = false;
  38950. _this.REFLECTION = false;
  38951. _this.EMISSIVE = false;
  38952. _this.EMISSIVEDIRECTUV = 0;
  38953. _this.SPECULAR = false;
  38954. _this.SPECULARDIRECTUV = 0;
  38955. _this.BUMP = false;
  38956. _this.BUMPDIRECTUV = 0;
  38957. _this.PARALLAX = false;
  38958. _this.PARALLAXOCCLUSION = false;
  38959. _this.SPECULAROVERALPHA = false;
  38960. _this.CLIPPLANE = false;
  38961. _this.ALPHATEST = false;
  38962. _this.DEPTHPREPASS = false;
  38963. _this.ALPHAFROMDIFFUSE = false;
  38964. _this.POINTSIZE = false;
  38965. _this.FOG = false;
  38966. _this.SPECULARTERM = false;
  38967. _this.DIFFUSEFRESNEL = false;
  38968. _this.OPACITYFRESNEL = false;
  38969. _this.REFLECTIONFRESNEL = false;
  38970. _this.REFRACTIONFRESNEL = false;
  38971. _this.EMISSIVEFRESNEL = false;
  38972. _this.FRESNEL = false;
  38973. _this.NORMAL = false;
  38974. _this.UV1 = false;
  38975. _this.UV2 = false;
  38976. _this.VERTEXCOLOR = false;
  38977. _this.VERTEXALPHA = false;
  38978. _this.NUM_BONE_INFLUENCERS = 0;
  38979. _this.BonesPerMesh = 0;
  38980. _this.INSTANCES = false;
  38981. _this.GLOSSINESS = false;
  38982. _this.ROUGHNESS = false;
  38983. _this.EMISSIVEASILLUMINATION = false;
  38984. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38985. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38986. _this.LIGHTMAP = false;
  38987. _this.LIGHTMAPDIRECTUV = 0;
  38988. _this.OBJECTSPACE_NORMALMAP = false;
  38989. _this.USELIGHTMAPASSHADOWMAP = false;
  38990. _this.REFLECTIONMAP_3D = false;
  38991. _this.REFLECTIONMAP_SPHERICAL = false;
  38992. _this.REFLECTIONMAP_PLANAR = false;
  38993. _this.REFLECTIONMAP_CUBIC = false;
  38994. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38995. _this.REFLECTIONMAP_PROJECTION = false;
  38996. _this.REFLECTIONMAP_SKYBOX = false;
  38997. _this.REFLECTIONMAP_EXPLICIT = false;
  38998. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38999. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39000. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39001. _this.INVERTCUBICMAP = false;
  39002. _this.LOGARITHMICDEPTH = false;
  39003. _this.REFRACTION = false;
  39004. _this.REFRACTIONMAP_3D = false;
  39005. _this.REFLECTIONOVERALPHA = false;
  39006. _this.TWOSIDEDLIGHTING = false;
  39007. _this.SHADOWFLOAT = false;
  39008. _this.MORPHTARGETS = false;
  39009. _this.MORPHTARGETS_NORMAL = false;
  39010. _this.MORPHTARGETS_TANGENT = false;
  39011. _this.NUM_MORPH_INFLUENCERS = 0;
  39012. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39013. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39014. _this.IMAGEPROCESSING = false;
  39015. _this.VIGNETTE = false;
  39016. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39017. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39018. _this.TONEMAPPING = false;
  39019. _this.CONTRAST = false;
  39020. _this.COLORCURVES = false;
  39021. _this.COLORGRADING = false;
  39022. _this.COLORGRADING3D = false;
  39023. _this.SAMPLER3DGREENDEPTH = false;
  39024. _this.SAMPLER3DBGRMAP = false;
  39025. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39026. _this.EXPOSURE = false;
  39027. _this.GRAIN = false;
  39028. _this.rebuild();
  39029. return _this;
  39030. }
  39031. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39032. var modes = [
  39033. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39034. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39035. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39036. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39037. ];
  39038. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39039. var mode = modes_1[_i];
  39040. this[mode] = (mode === modeToEnable);
  39041. }
  39042. };
  39043. return StandardMaterialDefines;
  39044. }(BABYLON.MaterialDefines));
  39045. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39046. var StandardMaterial = /** @class */ (function (_super) {
  39047. __extends(StandardMaterial, _super);
  39048. function StandardMaterial(name, scene) {
  39049. var _this = _super.call(this, name, scene) || this;
  39050. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39051. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39052. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39053. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39054. _this.specularPower = 64;
  39055. _this._useAlphaFromDiffuseTexture = false;
  39056. _this._useEmissiveAsIllumination = false;
  39057. _this._linkEmissiveWithDiffuse = false;
  39058. _this._useSpecularOverAlpha = false;
  39059. _this._useReflectionOverAlpha = false;
  39060. _this._disableLighting = false;
  39061. _this._useObjectSpaceNormalMap = false;
  39062. _this._useParallax = false;
  39063. _this._useParallaxOcclusion = false;
  39064. _this.parallaxScaleBias = 0.05;
  39065. _this._roughness = 0;
  39066. _this.indexOfRefraction = 0.98;
  39067. _this.invertRefractionY = true;
  39068. _this._useLightmapAsShadowmap = false;
  39069. _this._useReflectionFresnelFromSpecular = false;
  39070. _this._useGlossinessFromSpecularMapAlpha = false;
  39071. _this._maxSimultaneousLights = 4;
  39072. /**
  39073. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39074. */
  39075. _this._invertNormalMapX = false;
  39076. /**
  39077. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39078. */
  39079. _this._invertNormalMapY = false;
  39080. /**
  39081. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39082. */
  39083. _this._twoSidedLighting = false;
  39084. _this._renderTargets = new BABYLON.SmartArray(16);
  39085. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39086. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39087. // Setup the default processing configuration to the scene.
  39088. _this._attachImageProcessingConfiguration(null);
  39089. _this.getRenderTargetTextures = function () {
  39090. _this._renderTargets.reset();
  39091. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39092. _this._renderTargets.push(_this._reflectionTexture);
  39093. }
  39094. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39095. _this._renderTargets.push(_this._refractionTexture);
  39096. }
  39097. return _this._renderTargets;
  39098. };
  39099. return _this;
  39100. }
  39101. ;
  39102. ;
  39103. ;
  39104. ;
  39105. ;
  39106. ;
  39107. ;
  39108. ;
  39109. ;
  39110. ;
  39111. ;
  39112. ;
  39113. ;
  39114. ;
  39115. ;
  39116. ;
  39117. ;
  39118. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39119. /**
  39120. * Gets the image processing configuration used either in this material.
  39121. */
  39122. get: function () {
  39123. return this._imageProcessingConfiguration;
  39124. },
  39125. /**
  39126. * Sets the Default image processing configuration used either in the this material.
  39127. *
  39128. * If sets to null, the scene one is in use.
  39129. */
  39130. set: function (value) {
  39131. this._attachImageProcessingConfiguration(value);
  39132. // Ensure the effect will be rebuilt.
  39133. this._markAllSubMeshesAsTexturesDirty();
  39134. },
  39135. enumerable: true,
  39136. configurable: true
  39137. });
  39138. /**
  39139. * Attaches a new image processing configuration to the Standard Material.
  39140. * @param configuration
  39141. */
  39142. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39143. var _this = this;
  39144. if (configuration === this._imageProcessingConfiguration) {
  39145. return;
  39146. }
  39147. // Detaches observer.
  39148. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39149. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39150. }
  39151. // Pick the scene configuration if needed.
  39152. if (!configuration) {
  39153. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39154. }
  39155. else {
  39156. this._imageProcessingConfiguration = configuration;
  39157. }
  39158. // Attaches observer.
  39159. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39160. _this._markAllSubMeshesAsImageProcessingDirty();
  39161. });
  39162. };
  39163. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39164. /**
  39165. * Gets wether the color curves effect is enabled.
  39166. */
  39167. get: function () {
  39168. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39169. },
  39170. /**
  39171. * Sets wether the color curves effect is enabled.
  39172. */
  39173. set: function (value) {
  39174. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39180. /**
  39181. * Gets wether the color grading effect is enabled.
  39182. */
  39183. get: function () {
  39184. return this.imageProcessingConfiguration.colorGradingEnabled;
  39185. },
  39186. /**
  39187. * Gets wether the color grading effect is enabled.
  39188. */
  39189. set: function (value) {
  39190. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39191. },
  39192. enumerable: true,
  39193. configurable: true
  39194. });
  39195. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39196. /**
  39197. * Gets wether tonemapping is enabled or not.
  39198. */
  39199. get: function () {
  39200. return this._imageProcessingConfiguration.toneMappingEnabled;
  39201. },
  39202. /**
  39203. * Sets wether tonemapping is enabled or not
  39204. */
  39205. set: function (value) {
  39206. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39207. },
  39208. enumerable: true,
  39209. configurable: true
  39210. });
  39211. ;
  39212. ;
  39213. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39214. /**
  39215. * The camera exposure used on this material.
  39216. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39217. * This corresponds to a photographic exposure.
  39218. */
  39219. get: function () {
  39220. return this._imageProcessingConfiguration.exposure;
  39221. },
  39222. /**
  39223. * The camera exposure used on this material.
  39224. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39225. * This corresponds to a photographic exposure.
  39226. */
  39227. set: function (value) {
  39228. this._imageProcessingConfiguration.exposure = value;
  39229. },
  39230. enumerable: true,
  39231. configurable: true
  39232. });
  39233. ;
  39234. ;
  39235. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39236. /**
  39237. * Gets The camera contrast used on this material.
  39238. */
  39239. get: function () {
  39240. return this._imageProcessingConfiguration.contrast;
  39241. },
  39242. /**
  39243. * Sets The camera contrast used on this material.
  39244. */
  39245. set: function (value) {
  39246. this._imageProcessingConfiguration.contrast = value;
  39247. },
  39248. enumerable: true,
  39249. configurable: true
  39250. });
  39251. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39252. /**
  39253. * Gets the Color Grading 2D Lookup Texture.
  39254. */
  39255. get: function () {
  39256. return this._imageProcessingConfiguration.colorGradingTexture;
  39257. },
  39258. /**
  39259. * Sets the Color Grading 2D Lookup Texture.
  39260. */
  39261. set: function (value) {
  39262. this._imageProcessingConfiguration.colorGradingTexture = value;
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39268. /**
  39269. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39270. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39271. * 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;
  39272. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39273. */
  39274. get: function () {
  39275. return this._imageProcessingConfiguration.colorCurves;
  39276. },
  39277. /**
  39278. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39279. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39280. * 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;
  39281. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39282. */
  39283. set: function (value) {
  39284. this._imageProcessingConfiguration.colorCurves = value;
  39285. },
  39286. enumerable: true,
  39287. configurable: true
  39288. });
  39289. StandardMaterial.prototype.getClassName = function () {
  39290. return "StandardMaterial";
  39291. };
  39292. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39293. get: function () {
  39294. return this._useLogarithmicDepth;
  39295. },
  39296. set: function (value) {
  39297. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39298. this._markAllSubMeshesAsMiscDirty();
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. StandardMaterial.prototype.needAlphaBlending = function () {
  39304. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39305. };
  39306. StandardMaterial.prototype.needAlphaTesting = function () {
  39307. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39308. };
  39309. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39310. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39311. };
  39312. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39313. return this._diffuseTexture;
  39314. };
  39315. /**
  39316. * Child classes can use it to update shaders
  39317. */
  39318. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39319. if (useInstances === void 0) { useInstances = false; }
  39320. if (subMesh.effect && this.isFrozen) {
  39321. if (this._wasPreviouslyReady && subMesh.effect) {
  39322. return true;
  39323. }
  39324. }
  39325. if (!subMesh._materialDefines) {
  39326. subMesh._materialDefines = new StandardMaterialDefines();
  39327. }
  39328. var scene = this.getScene();
  39329. var defines = subMesh._materialDefines;
  39330. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39331. if (defines._renderId === scene.getRenderId()) {
  39332. return true;
  39333. }
  39334. }
  39335. var engine = scene.getEngine();
  39336. // Lights
  39337. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39338. // Textures
  39339. if (defines._areTexturesDirty) {
  39340. defines._needUVs = false;
  39341. defines.MAINUV1 = false;
  39342. defines.MAINUV2 = false;
  39343. if (scene.texturesEnabled) {
  39344. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39345. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39346. return false;
  39347. }
  39348. else {
  39349. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39350. }
  39351. }
  39352. else {
  39353. defines.DIFFUSE = false;
  39354. }
  39355. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39356. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39357. return false;
  39358. }
  39359. else {
  39360. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39361. }
  39362. }
  39363. else {
  39364. defines.AMBIENT = false;
  39365. }
  39366. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39367. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39368. return false;
  39369. }
  39370. else {
  39371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39372. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39373. }
  39374. }
  39375. else {
  39376. defines.OPACITY = false;
  39377. }
  39378. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39379. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39380. return false;
  39381. }
  39382. else {
  39383. defines._needNormals = true;
  39384. defines.REFLECTION = true;
  39385. defines.ROUGHNESS = (this._roughness > 0);
  39386. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39387. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39388. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39389. switch (this._reflectionTexture.coordinatesMode) {
  39390. case BABYLON.Texture.CUBIC_MODE:
  39391. case BABYLON.Texture.INVCUBIC_MODE:
  39392. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39393. break;
  39394. case BABYLON.Texture.EXPLICIT_MODE:
  39395. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39396. break;
  39397. case BABYLON.Texture.PLANAR_MODE:
  39398. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39399. break;
  39400. case BABYLON.Texture.PROJECTION_MODE:
  39401. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39402. break;
  39403. case BABYLON.Texture.SKYBOX_MODE:
  39404. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39405. break;
  39406. case BABYLON.Texture.SPHERICAL_MODE:
  39407. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39408. break;
  39409. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39410. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39411. break;
  39412. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39413. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39414. break;
  39415. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39416. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39417. break;
  39418. }
  39419. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39420. }
  39421. }
  39422. else {
  39423. defines.REFLECTION = false;
  39424. }
  39425. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39426. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39427. return false;
  39428. }
  39429. else {
  39430. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39431. }
  39432. }
  39433. else {
  39434. defines.EMISSIVE = false;
  39435. }
  39436. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39437. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39438. return false;
  39439. }
  39440. else {
  39441. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39442. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39443. }
  39444. }
  39445. else {
  39446. defines.LIGHTMAP = false;
  39447. }
  39448. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39449. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39450. return false;
  39451. }
  39452. else {
  39453. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39454. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39455. }
  39456. }
  39457. else {
  39458. defines.SPECULAR = false;
  39459. }
  39460. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39461. // Bump texure can not be not blocking.
  39462. if (!this._bumpTexture.isReady()) {
  39463. return false;
  39464. }
  39465. else {
  39466. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39467. defines.PARALLAX = this._useParallax;
  39468. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39469. }
  39470. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39471. }
  39472. else {
  39473. defines.BUMP = false;
  39474. }
  39475. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39476. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39477. return false;
  39478. }
  39479. else {
  39480. defines._needUVs = true;
  39481. defines.REFRACTION = true;
  39482. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39483. }
  39484. }
  39485. else {
  39486. defines.REFRACTION = false;
  39487. }
  39488. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39489. }
  39490. else {
  39491. defines.DIFFUSE = false;
  39492. defines.AMBIENT = false;
  39493. defines.OPACITY = false;
  39494. defines.REFLECTION = false;
  39495. defines.EMISSIVE = false;
  39496. defines.LIGHTMAP = false;
  39497. defines.BUMP = false;
  39498. defines.REFRACTION = false;
  39499. }
  39500. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39501. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39502. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39503. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39504. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39505. }
  39506. if (defines._areImageProcessingDirty) {
  39507. if (!this._imageProcessingConfiguration.isReady()) {
  39508. return false;
  39509. }
  39510. this._imageProcessingConfiguration.prepareDefines(defines);
  39511. }
  39512. if (defines._areFresnelDirty) {
  39513. if (StandardMaterial.FresnelEnabled) {
  39514. // Fresnel
  39515. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39516. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39517. this._reflectionFresnelParameters) {
  39518. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39519. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39520. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39521. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39522. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39523. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39524. defines._needNormals = true;
  39525. defines.FRESNEL = true;
  39526. }
  39527. }
  39528. else {
  39529. defines.FRESNEL = false;
  39530. }
  39531. }
  39532. // Misc.
  39533. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39534. // Attribs
  39535. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39536. // Values that need to be evaluated on every frame
  39537. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39538. // Get correct effect
  39539. if (defines.isDirty) {
  39540. defines.markAsProcessed();
  39541. scene.resetCachedMaterial();
  39542. // Fallbacks
  39543. var fallbacks = new BABYLON.EffectFallbacks();
  39544. if (defines.REFLECTION) {
  39545. fallbacks.addFallback(0, "REFLECTION");
  39546. }
  39547. if (defines.SPECULAR) {
  39548. fallbacks.addFallback(0, "SPECULAR");
  39549. }
  39550. if (defines.BUMP) {
  39551. fallbacks.addFallback(0, "BUMP");
  39552. }
  39553. if (defines.PARALLAX) {
  39554. fallbacks.addFallback(1, "PARALLAX");
  39555. }
  39556. if (defines.PARALLAXOCCLUSION) {
  39557. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39558. }
  39559. if (defines.SPECULAROVERALPHA) {
  39560. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39561. }
  39562. if (defines.FOG) {
  39563. fallbacks.addFallback(1, "FOG");
  39564. }
  39565. if (defines.POINTSIZE) {
  39566. fallbacks.addFallback(0, "POINTSIZE");
  39567. }
  39568. if (defines.LOGARITHMICDEPTH) {
  39569. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39570. }
  39571. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39572. if (defines.SPECULARTERM) {
  39573. fallbacks.addFallback(0, "SPECULARTERM");
  39574. }
  39575. if (defines.DIFFUSEFRESNEL) {
  39576. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39577. }
  39578. if (defines.OPACITYFRESNEL) {
  39579. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39580. }
  39581. if (defines.REFLECTIONFRESNEL) {
  39582. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39583. }
  39584. if (defines.EMISSIVEFRESNEL) {
  39585. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39586. }
  39587. if (defines.FRESNEL) {
  39588. fallbacks.addFallback(4, "FRESNEL");
  39589. }
  39590. //Attributes
  39591. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39592. if (defines.NORMAL) {
  39593. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39594. }
  39595. if (defines.UV1) {
  39596. attribs.push(BABYLON.VertexBuffer.UVKind);
  39597. }
  39598. if (defines.UV2) {
  39599. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39600. }
  39601. if (defines.VERTEXCOLOR) {
  39602. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39603. }
  39604. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39605. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39606. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39607. var shaderName = "default";
  39608. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39609. "vFogInfos", "vFogColor", "pointSize",
  39610. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39611. "mBones",
  39612. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39613. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39614. "vReflectionPosition", "vReflectionSize",
  39615. "logarithmicDepthConstant", "vTangentSpaceParams"
  39616. ];
  39617. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39618. var uniformBuffers = ["Material", "Scene"];
  39619. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39620. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39621. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39622. uniformsNames: uniforms,
  39623. uniformBuffersNames: uniformBuffers,
  39624. samplers: samplers,
  39625. defines: defines,
  39626. maxSimultaneousLights: this._maxSimultaneousLights
  39627. });
  39628. if (this.customShaderNameResolve) {
  39629. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39630. }
  39631. var join = defines.toString();
  39632. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39633. attributes: attribs,
  39634. uniformsNames: uniforms,
  39635. uniformBuffersNames: uniformBuffers,
  39636. samplers: samplers,
  39637. defines: join,
  39638. fallbacks: fallbacks,
  39639. onCompiled: this.onCompiled,
  39640. onError: this.onError,
  39641. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39642. }, engine), defines);
  39643. this.buildUniformLayout();
  39644. }
  39645. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39646. return false;
  39647. }
  39648. defines._renderId = scene.getRenderId();
  39649. this._wasPreviouslyReady = true;
  39650. return true;
  39651. };
  39652. StandardMaterial.prototype.buildUniformLayout = function () {
  39653. // Order is important !
  39654. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39655. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39656. this._uniformBuffer.addUniform("opacityParts", 4);
  39657. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39658. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39659. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39660. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39661. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39662. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39663. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39664. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39665. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39666. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39667. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39668. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39669. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39670. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39671. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39672. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39673. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39674. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39675. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39676. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39677. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39678. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39679. this._uniformBuffer.addUniform("specularMatrix", 16);
  39680. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39681. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39682. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39683. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39684. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39685. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39686. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39687. this._uniformBuffer.addUniform("pointSize", 1);
  39688. this._uniformBuffer.create();
  39689. };
  39690. StandardMaterial.prototype.unbind = function () {
  39691. if (this._activeEffect) {
  39692. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39693. this._activeEffect.setTexture("reflection2DSampler", null);
  39694. }
  39695. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39696. this._activeEffect.setTexture("refraction2DSampler", null);
  39697. }
  39698. }
  39699. _super.prototype.unbind.call(this);
  39700. };
  39701. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39702. var scene = this.getScene();
  39703. var defines = subMesh._materialDefines;
  39704. if (!defines) {
  39705. return;
  39706. }
  39707. var effect = subMesh.effect;
  39708. if (!effect) {
  39709. return;
  39710. }
  39711. this._activeEffect = effect;
  39712. // Matrices
  39713. this.bindOnlyWorldMatrix(world);
  39714. // Normal Matrix
  39715. if (defines.OBJECTSPACE_NORMALMAP) {
  39716. world.toNormalMatrix(this._normalMatrix);
  39717. this.bindOnlyNormalMatrix(this._normalMatrix);
  39718. }
  39719. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39720. // Bones
  39721. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39722. if (mustRebind) {
  39723. this._uniformBuffer.bindToEffect(effect, "Material");
  39724. this.bindViewProjection(effect);
  39725. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39726. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39727. // Fresnel
  39728. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39729. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39730. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39731. }
  39732. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39733. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39734. }
  39735. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39736. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39737. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39738. }
  39739. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39740. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39741. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39742. }
  39743. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39744. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39745. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39746. }
  39747. }
  39748. // Textures
  39749. if (scene.texturesEnabled) {
  39750. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39751. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39752. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39753. }
  39754. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39755. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39756. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39757. }
  39758. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39759. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39760. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39761. }
  39762. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39763. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39764. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39765. if (this._reflectionTexture.boundingBoxSize) {
  39766. var cubeTexture = this._reflectionTexture;
  39767. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39768. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39769. }
  39770. }
  39771. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39772. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39773. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39774. }
  39775. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39776. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39777. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39778. }
  39779. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39780. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39781. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39782. }
  39783. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39784. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39785. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39786. if (scene._mirroredCameraPosition) {
  39787. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39788. }
  39789. else {
  39790. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39791. }
  39792. }
  39793. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39794. var depth = 1.0;
  39795. if (!this._refractionTexture.isCube) {
  39796. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39797. if (this._refractionTexture.depth) {
  39798. depth = this._refractionTexture.depth;
  39799. }
  39800. }
  39801. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39802. }
  39803. }
  39804. // Point size
  39805. if (this.pointsCloud) {
  39806. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39807. }
  39808. if (defines.SPECULARTERM) {
  39809. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39810. }
  39811. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39812. // Diffuse
  39813. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39814. }
  39815. // Textures
  39816. if (scene.texturesEnabled) {
  39817. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39818. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39819. }
  39820. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39821. effect.setTexture("ambientSampler", this._ambientTexture);
  39822. }
  39823. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39824. effect.setTexture("opacitySampler", this._opacityTexture);
  39825. }
  39826. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39827. if (this._reflectionTexture.isCube) {
  39828. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39829. }
  39830. else {
  39831. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39832. }
  39833. }
  39834. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39835. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39836. }
  39837. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39838. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39839. }
  39840. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39841. effect.setTexture("specularSampler", this._specularTexture);
  39842. }
  39843. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39844. effect.setTexture("bumpSampler", this._bumpTexture);
  39845. }
  39846. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39847. var depth = 1.0;
  39848. if (this._refractionTexture.isCube) {
  39849. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39850. }
  39851. else {
  39852. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39853. }
  39854. }
  39855. }
  39856. // Clip plane
  39857. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39858. // Colors
  39859. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39860. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39861. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39862. }
  39863. if (mustRebind || !this.isFrozen) {
  39864. // Lights
  39865. if (scene.lightsEnabled && !this._disableLighting) {
  39866. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39867. }
  39868. // View
  39869. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39870. this.bindView(effect);
  39871. }
  39872. // Fog
  39873. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39874. // Morph targets
  39875. if (defines.NUM_MORPH_INFLUENCERS) {
  39876. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39877. }
  39878. // Log. depth
  39879. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39880. // image processing
  39881. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39882. this._imageProcessingConfiguration.bind(this._activeEffect);
  39883. }
  39884. }
  39885. this._uniformBuffer.update();
  39886. this._afterBind(mesh, this._activeEffect);
  39887. };
  39888. StandardMaterial.prototype.getAnimatables = function () {
  39889. var results = [];
  39890. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39891. results.push(this._diffuseTexture);
  39892. }
  39893. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39894. results.push(this._ambientTexture);
  39895. }
  39896. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39897. results.push(this._opacityTexture);
  39898. }
  39899. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39900. results.push(this._reflectionTexture);
  39901. }
  39902. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39903. results.push(this._emissiveTexture);
  39904. }
  39905. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39906. results.push(this._specularTexture);
  39907. }
  39908. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39909. results.push(this._bumpTexture);
  39910. }
  39911. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39912. results.push(this._lightmapTexture);
  39913. }
  39914. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39915. results.push(this._refractionTexture);
  39916. }
  39917. return results;
  39918. };
  39919. StandardMaterial.prototype.getActiveTextures = function () {
  39920. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39921. if (this._diffuseTexture) {
  39922. activeTextures.push(this._diffuseTexture);
  39923. }
  39924. if (this._ambientTexture) {
  39925. activeTextures.push(this._ambientTexture);
  39926. }
  39927. if (this._opacityTexture) {
  39928. activeTextures.push(this._opacityTexture);
  39929. }
  39930. if (this._reflectionTexture) {
  39931. activeTextures.push(this._reflectionTexture);
  39932. }
  39933. if (this._emissiveTexture) {
  39934. activeTextures.push(this._emissiveTexture);
  39935. }
  39936. if (this._specularTexture) {
  39937. activeTextures.push(this._specularTexture);
  39938. }
  39939. if (this._bumpTexture) {
  39940. activeTextures.push(this._bumpTexture);
  39941. }
  39942. if (this._lightmapTexture) {
  39943. activeTextures.push(this._lightmapTexture);
  39944. }
  39945. if (this._refractionTexture) {
  39946. activeTextures.push(this._refractionTexture);
  39947. }
  39948. return activeTextures;
  39949. };
  39950. StandardMaterial.prototype.hasTexture = function (texture) {
  39951. if (_super.prototype.hasTexture.call(this, texture)) {
  39952. return true;
  39953. }
  39954. if (this._diffuseTexture === texture) {
  39955. return true;
  39956. }
  39957. if (this._ambientTexture === texture) {
  39958. return true;
  39959. }
  39960. if (this._opacityTexture === texture) {
  39961. return true;
  39962. }
  39963. if (this._reflectionTexture === texture) {
  39964. return true;
  39965. }
  39966. if (this._emissiveTexture === texture) {
  39967. return true;
  39968. }
  39969. if (this._specularTexture === texture) {
  39970. return true;
  39971. }
  39972. if (this._bumpTexture === texture) {
  39973. return true;
  39974. }
  39975. if (this._lightmapTexture === texture) {
  39976. return true;
  39977. }
  39978. if (this._refractionTexture === texture) {
  39979. return true;
  39980. }
  39981. return false;
  39982. };
  39983. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39984. if (forceDisposeTextures) {
  39985. if (this._diffuseTexture) {
  39986. this._diffuseTexture.dispose();
  39987. }
  39988. if (this._ambientTexture) {
  39989. this._ambientTexture.dispose();
  39990. }
  39991. if (this._opacityTexture) {
  39992. this._opacityTexture.dispose();
  39993. }
  39994. if (this._reflectionTexture) {
  39995. this._reflectionTexture.dispose();
  39996. }
  39997. if (this._emissiveTexture) {
  39998. this._emissiveTexture.dispose();
  39999. }
  40000. if (this._specularTexture) {
  40001. this._specularTexture.dispose();
  40002. }
  40003. if (this._bumpTexture) {
  40004. this._bumpTexture.dispose();
  40005. }
  40006. if (this._lightmapTexture) {
  40007. this._lightmapTexture.dispose();
  40008. }
  40009. if (this._refractionTexture) {
  40010. this._refractionTexture.dispose();
  40011. }
  40012. }
  40013. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40014. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40015. }
  40016. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40017. };
  40018. StandardMaterial.prototype.clone = function (name) {
  40019. var _this = this;
  40020. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40021. result.name = name;
  40022. result.id = name;
  40023. return result;
  40024. };
  40025. StandardMaterial.prototype.serialize = function () {
  40026. return BABYLON.SerializationHelper.Serialize(this);
  40027. };
  40028. // Statics
  40029. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40030. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40031. };
  40032. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40033. get: function () {
  40034. return StandardMaterial._DiffuseTextureEnabled;
  40035. },
  40036. set: function (value) {
  40037. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40038. return;
  40039. }
  40040. StandardMaterial._DiffuseTextureEnabled = value;
  40041. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40042. },
  40043. enumerable: true,
  40044. configurable: true
  40045. });
  40046. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40047. get: function () {
  40048. return StandardMaterial._AmbientTextureEnabled;
  40049. },
  40050. set: function (value) {
  40051. if (StandardMaterial._AmbientTextureEnabled === value) {
  40052. return;
  40053. }
  40054. StandardMaterial._AmbientTextureEnabled = value;
  40055. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40056. },
  40057. enumerable: true,
  40058. configurable: true
  40059. });
  40060. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40061. get: function () {
  40062. return StandardMaterial._OpacityTextureEnabled;
  40063. },
  40064. set: function (value) {
  40065. if (StandardMaterial._OpacityTextureEnabled === value) {
  40066. return;
  40067. }
  40068. StandardMaterial._OpacityTextureEnabled = value;
  40069. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40070. },
  40071. enumerable: true,
  40072. configurable: true
  40073. });
  40074. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40075. get: function () {
  40076. return StandardMaterial._ReflectionTextureEnabled;
  40077. },
  40078. set: function (value) {
  40079. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40080. return;
  40081. }
  40082. StandardMaterial._ReflectionTextureEnabled = value;
  40083. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40084. },
  40085. enumerable: true,
  40086. configurable: true
  40087. });
  40088. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40089. get: function () {
  40090. return StandardMaterial._EmissiveTextureEnabled;
  40091. },
  40092. set: function (value) {
  40093. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40094. return;
  40095. }
  40096. StandardMaterial._EmissiveTextureEnabled = value;
  40097. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40098. },
  40099. enumerable: true,
  40100. configurable: true
  40101. });
  40102. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40103. get: function () {
  40104. return StandardMaterial._SpecularTextureEnabled;
  40105. },
  40106. set: function (value) {
  40107. if (StandardMaterial._SpecularTextureEnabled === value) {
  40108. return;
  40109. }
  40110. StandardMaterial._SpecularTextureEnabled = value;
  40111. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40112. },
  40113. enumerable: true,
  40114. configurable: true
  40115. });
  40116. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40117. get: function () {
  40118. return StandardMaterial._BumpTextureEnabled;
  40119. },
  40120. set: function (value) {
  40121. if (StandardMaterial._BumpTextureEnabled === value) {
  40122. return;
  40123. }
  40124. StandardMaterial._BumpTextureEnabled = value;
  40125. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40126. },
  40127. enumerable: true,
  40128. configurable: true
  40129. });
  40130. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40131. get: function () {
  40132. return StandardMaterial._LightmapTextureEnabled;
  40133. },
  40134. set: function (value) {
  40135. if (StandardMaterial._LightmapTextureEnabled === value) {
  40136. return;
  40137. }
  40138. StandardMaterial._LightmapTextureEnabled = value;
  40139. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40140. },
  40141. enumerable: true,
  40142. configurable: true
  40143. });
  40144. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40145. get: function () {
  40146. return StandardMaterial._RefractionTextureEnabled;
  40147. },
  40148. set: function (value) {
  40149. if (StandardMaterial._RefractionTextureEnabled === value) {
  40150. return;
  40151. }
  40152. StandardMaterial._RefractionTextureEnabled = value;
  40153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40154. },
  40155. enumerable: true,
  40156. configurable: true
  40157. });
  40158. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40159. get: function () {
  40160. return StandardMaterial._ColorGradingTextureEnabled;
  40161. },
  40162. set: function (value) {
  40163. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40164. return;
  40165. }
  40166. StandardMaterial._ColorGradingTextureEnabled = value;
  40167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40168. },
  40169. enumerable: true,
  40170. configurable: true
  40171. });
  40172. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40173. get: function () {
  40174. return StandardMaterial._FresnelEnabled;
  40175. },
  40176. set: function (value) {
  40177. if (StandardMaterial._FresnelEnabled === value) {
  40178. return;
  40179. }
  40180. StandardMaterial._FresnelEnabled = value;
  40181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40182. },
  40183. enumerable: true,
  40184. configurable: true
  40185. });
  40186. // Flags used to enable or disable a type of texture for all Standard Materials
  40187. StandardMaterial._DiffuseTextureEnabled = true;
  40188. StandardMaterial._AmbientTextureEnabled = true;
  40189. StandardMaterial._OpacityTextureEnabled = true;
  40190. StandardMaterial._ReflectionTextureEnabled = true;
  40191. StandardMaterial._EmissiveTextureEnabled = true;
  40192. StandardMaterial._SpecularTextureEnabled = true;
  40193. StandardMaterial._BumpTextureEnabled = true;
  40194. StandardMaterial._LightmapTextureEnabled = true;
  40195. StandardMaterial._RefractionTextureEnabled = true;
  40196. StandardMaterial._ColorGradingTextureEnabled = true;
  40197. StandardMaterial._FresnelEnabled = true;
  40198. __decorate([
  40199. BABYLON.serializeAsTexture("diffuseTexture")
  40200. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40201. __decorate([
  40202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40203. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40204. __decorate([
  40205. BABYLON.serializeAsTexture("ambientTexture")
  40206. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40207. __decorate([
  40208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40209. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40210. __decorate([
  40211. BABYLON.serializeAsTexture("opacityTexture")
  40212. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40213. __decorate([
  40214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40215. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40216. __decorate([
  40217. BABYLON.serializeAsTexture("reflectionTexture")
  40218. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40219. __decorate([
  40220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40221. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40222. __decorate([
  40223. BABYLON.serializeAsTexture("emissiveTexture")
  40224. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40225. __decorate([
  40226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40227. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40228. __decorate([
  40229. BABYLON.serializeAsTexture("specularTexture")
  40230. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40231. __decorate([
  40232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40233. ], StandardMaterial.prototype, "specularTexture", void 0);
  40234. __decorate([
  40235. BABYLON.serializeAsTexture("bumpTexture")
  40236. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40237. __decorate([
  40238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40239. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40240. __decorate([
  40241. BABYLON.serializeAsTexture("lightmapTexture")
  40242. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40243. __decorate([
  40244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40245. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40246. __decorate([
  40247. BABYLON.serializeAsTexture("refractionTexture")
  40248. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40249. __decorate([
  40250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40251. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40252. __decorate([
  40253. BABYLON.serializeAsColor3("ambient")
  40254. ], StandardMaterial.prototype, "ambientColor", void 0);
  40255. __decorate([
  40256. BABYLON.serializeAsColor3("diffuse")
  40257. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40258. __decorate([
  40259. BABYLON.serializeAsColor3("specular")
  40260. ], StandardMaterial.prototype, "specularColor", void 0);
  40261. __decorate([
  40262. BABYLON.serializeAsColor3("emissive")
  40263. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40264. __decorate([
  40265. BABYLON.serialize()
  40266. ], StandardMaterial.prototype, "specularPower", void 0);
  40267. __decorate([
  40268. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40269. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40270. __decorate([
  40271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40272. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40273. __decorate([
  40274. BABYLON.serialize("useEmissiveAsIllumination")
  40275. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40276. __decorate([
  40277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40278. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40279. __decorate([
  40280. BABYLON.serialize("linkEmissiveWithDiffuse")
  40281. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40282. __decorate([
  40283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40284. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40285. __decorate([
  40286. BABYLON.serialize("useSpecularOverAlpha")
  40287. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40288. __decorate([
  40289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40290. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40291. __decorate([
  40292. BABYLON.serialize("useReflectionOverAlpha")
  40293. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40294. __decorate([
  40295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40296. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40297. __decorate([
  40298. BABYLON.serialize("disableLighting")
  40299. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40300. __decorate([
  40301. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40302. ], StandardMaterial.prototype, "disableLighting", void 0);
  40303. __decorate([
  40304. BABYLON.serialize("useObjectSpaceNormalMap")
  40305. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40306. __decorate([
  40307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40308. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40309. __decorate([
  40310. BABYLON.serialize("useParallax")
  40311. ], StandardMaterial.prototype, "_useParallax", void 0);
  40312. __decorate([
  40313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40314. ], StandardMaterial.prototype, "useParallax", void 0);
  40315. __decorate([
  40316. BABYLON.serialize("useParallaxOcclusion")
  40317. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40318. __decorate([
  40319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40320. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40321. __decorate([
  40322. BABYLON.serialize()
  40323. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40324. __decorate([
  40325. BABYLON.serialize("roughness")
  40326. ], StandardMaterial.prototype, "_roughness", void 0);
  40327. __decorate([
  40328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40329. ], StandardMaterial.prototype, "roughness", void 0);
  40330. __decorate([
  40331. BABYLON.serialize()
  40332. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40333. __decorate([
  40334. BABYLON.serialize()
  40335. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40336. __decorate([
  40337. BABYLON.serialize("useLightmapAsShadowmap")
  40338. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40339. __decorate([
  40340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40341. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40342. __decorate([
  40343. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40344. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40345. __decorate([
  40346. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40347. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40348. __decorate([
  40349. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40350. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40351. __decorate([
  40352. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40353. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40354. __decorate([
  40355. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40356. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40357. __decorate([
  40358. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40359. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40360. __decorate([
  40361. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40362. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40363. __decorate([
  40364. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40365. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40366. __decorate([
  40367. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40368. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40369. __decorate([
  40370. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40371. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40372. __decorate([
  40373. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40374. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40375. __decorate([
  40376. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40377. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40378. __decorate([
  40379. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40380. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40381. __decorate([
  40382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40383. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40384. __decorate([
  40385. BABYLON.serialize("maxSimultaneousLights")
  40386. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40387. __decorate([
  40388. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40389. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40390. __decorate([
  40391. BABYLON.serialize("invertNormalMapX")
  40392. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40393. __decorate([
  40394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40395. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40396. __decorate([
  40397. BABYLON.serialize("invertNormalMapY")
  40398. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40399. __decorate([
  40400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40401. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40402. __decorate([
  40403. BABYLON.serialize("twoSidedLighting")
  40404. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40405. __decorate([
  40406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40407. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40408. __decorate([
  40409. BABYLON.serialize()
  40410. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40411. return StandardMaterial;
  40412. }(BABYLON.PushMaterial));
  40413. BABYLON.StandardMaterial = StandardMaterial;
  40414. })(BABYLON || (BABYLON = {}));
  40415. //# sourceMappingURL=babylon.standardMaterial.js.map
  40416. var BABYLON;
  40417. (function (BABYLON) {
  40418. /**
  40419. * Manages the defines for the PBR Material.
  40420. */
  40421. var PBRMaterialDefines = /** @class */ (function (_super) {
  40422. __extends(PBRMaterialDefines, _super);
  40423. /**
  40424. * Initializes the PBR Material defines.
  40425. */
  40426. function PBRMaterialDefines() {
  40427. var _this = _super.call(this) || this;
  40428. _this.PBR = true;
  40429. _this.MAINUV1 = false;
  40430. _this.MAINUV2 = false;
  40431. _this.UV1 = false;
  40432. _this.UV2 = false;
  40433. _this.ALBEDO = false;
  40434. _this.ALBEDODIRECTUV = 0;
  40435. _this.VERTEXCOLOR = false;
  40436. _this.AMBIENT = false;
  40437. _this.AMBIENTDIRECTUV = 0;
  40438. _this.AMBIENTINGRAYSCALE = false;
  40439. _this.OPACITY = false;
  40440. _this.VERTEXALPHA = false;
  40441. _this.OPACITYDIRECTUV = 0;
  40442. _this.OPACITYRGB = false;
  40443. _this.ALPHATEST = false;
  40444. _this.DEPTHPREPASS = false;
  40445. _this.ALPHABLEND = false;
  40446. _this.ALPHAFROMALBEDO = false;
  40447. _this.ALPHATESTVALUE = 0.5;
  40448. _this.SPECULAROVERALPHA = false;
  40449. _this.RADIANCEOVERALPHA = false;
  40450. _this.ALPHAFRESNEL = false;
  40451. _this.LINEARALPHAFRESNEL = false;
  40452. _this.PREMULTIPLYALPHA = false;
  40453. _this.EMISSIVE = false;
  40454. _this.EMISSIVEDIRECTUV = 0;
  40455. _this.REFLECTIVITY = false;
  40456. _this.REFLECTIVITYDIRECTUV = 0;
  40457. _this.SPECULARTERM = false;
  40458. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40459. _this.MICROSURFACEAUTOMATIC = false;
  40460. _this.LODBASEDMICROSFURACE = false;
  40461. _this.MICROSURFACEMAP = false;
  40462. _this.MICROSURFACEMAPDIRECTUV = 0;
  40463. _this.METALLICWORKFLOW = false;
  40464. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40465. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40466. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40467. _this.AOSTOREINMETALMAPRED = false;
  40468. _this.ENVIRONMENTBRDF = false;
  40469. _this.NORMAL = false;
  40470. _this.TANGENT = false;
  40471. _this.BUMP = false;
  40472. _this.BUMPDIRECTUV = 0;
  40473. _this.OBJECTSPACE_NORMALMAP = false;
  40474. _this.PARALLAX = false;
  40475. _this.PARALLAXOCCLUSION = false;
  40476. _this.NORMALXYSCALE = true;
  40477. _this.LIGHTMAP = false;
  40478. _this.LIGHTMAPDIRECTUV = 0;
  40479. _this.USELIGHTMAPASSHADOWMAP = false;
  40480. _this.REFLECTION = false;
  40481. _this.REFLECTIONMAP_3D = false;
  40482. _this.REFLECTIONMAP_SPHERICAL = false;
  40483. _this.REFLECTIONMAP_PLANAR = false;
  40484. _this.REFLECTIONMAP_CUBIC = false;
  40485. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40486. _this.REFLECTIONMAP_PROJECTION = false;
  40487. _this.REFLECTIONMAP_SKYBOX = false;
  40488. _this.REFLECTIONMAP_EXPLICIT = false;
  40489. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40490. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40491. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40492. _this.INVERTCUBICMAP = false;
  40493. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40494. _this.USESPHERICALINVERTEX = false;
  40495. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40496. _this.LODINREFLECTIONALPHA = false;
  40497. _this.GAMMAREFLECTION = false;
  40498. _this.RADIANCEOCCLUSION = false;
  40499. _this.HORIZONOCCLUSION = false;
  40500. _this.REFRACTION = false;
  40501. _this.REFRACTIONMAP_3D = false;
  40502. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40503. _this.LODINREFRACTIONALPHA = false;
  40504. _this.GAMMAREFRACTION = false;
  40505. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40506. _this.INSTANCES = false;
  40507. _this.NUM_BONE_INFLUENCERS = 0;
  40508. _this.BonesPerMesh = 0;
  40509. _this.NONUNIFORMSCALING = false;
  40510. _this.MORPHTARGETS = false;
  40511. _this.MORPHTARGETS_NORMAL = false;
  40512. _this.MORPHTARGETS_TANGENT = false;
  40513. _this.NUM_MORPH_INFLUENCERS = 0;
  40514. _this.IMAGEPROCESSING = false;
  40515. _this.VIGNETTE = false;
  40516. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40517. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40518. _this.TONEMAPPING = false;
  40519. _this.CONTRAST = false;
  40520. _this.COLORCURVES = false;
  40521. _this.COLORGRADING = false;
  40522. _this.COLORGRADING3D = false;
  40523. _this.SAMPLER3DGREENDEPTH = false;
  40524. _this.SAMPLER3DBGRMAP = false;
  40525. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40526. _this.EXPOSURE = false;
  40527. _this.GRAIN = false;
  40528. _this.USEPHYSICALLIGHTFALLOFF = false;
  40529. _this.TWOSIDEDLIGHTING = false;
  40530. _this.SHADOWFLOAT = false;
  40531. _this.CLIPPLANE = false;
  40532. _this.POINTSIZE = false;
  40533. _this.FOG = false;
  40534. _this.LOGARITHMICDEPTH = false;
  40535. _this.FORCENORMALFORWARD = false;
  40536. _this.rebuild();
  40537. return _this;
  40538. }
  40539. /**
  40540. * Resets the PBR Material defines.
  40541. */
  40542. PBRMaterialDefines.prototype.reset = function () {
  40543. _super.prototype.reset.call(this);
  40544. this.ALPHATESTVALUE = 0.5;
  40545. this.PBR = true;
  40546. };
  40547. return PBRMaterialDefines;
  40548. }(BABYLON.MaterialDefines));
  40549. /**
  40550. * The Physically based material base class of BJS.
  40551. *
  40552. * This offers the main features of a standard PBR material.
  40553. * For more information, please refer to the documentation :
  40554. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40555. */
  40556. var PBRBaseMaterial = /** @class */ (function (_super) {
  40557. __extends(PBRBaseMaterial, _super);
  40558. /**
  40559. * Instantiates a new PBRMaterial instance.
  40560. *
  40561. * @param name The material name
  40562. * @param scene The scene the material will be use in.
  40563. */
  40564. function PBRBaseMaterial(name, scene) {
  40565. var _this = _super.call(this, name, scene) || this;
  40566. /**
  40567. * Intensity of the direct lights e.g. the four lights available in your scene.
  40568. * This impacts both the direct diffuse and specular highlights.
  40569. */
  40570. _this._directIntensity = 1.0;
  40571. /**
  40572. * Intensity of the emissive part of the material.
  40573. * This helps controlling the emissive effect without modifying the emissive color.
  40574. */
  40575. _this._emissiveIntensity = 1.0;
  40576. /**
  40577. * Intensity of the environment e.g. how much the environment will light the object
  40578. * either through harmonics for rough material or through the refelction for shiny ones.
  40579. */
  40580. _this._environmentIntensity = 1.0;
  40581. /**
  40582. * This is a special control allowing the reduction of the specular highlights coming from the
  40583. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40584. */
  40585. _this._specularIntensity = 1.0;
  40586. /**
  40587. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40588. */
  40589. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40590. /**
  40591. * Debug Control allowing disabling the bump map on this material.
  40592. */
  40593. _this._disableBumpMap = false;
  40594. /**
  40595. * AKA Occlusion Texture Intensity in other nomenclature.
  40596. */
  40597. _this._ambientTextureStrength = 1.0;
  40598. /**
  40599. * The color of a material in ambient lighting.
  40600. */
  40601. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40602. /**
  40603. * AKA Diffuse Color in other nomenclature.
  40604. */
  40605. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40606. /**
  40607. * AKA Specular Color in other nomenclature.
  40608. */
  40609. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40610. /**
  40611. * The color applied when light is reflected from a material.
  40612. */
  40613. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40614. /**
  40615. * The color applied when light is emitted from a material.
  40616. */
  40617. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40618. /**
  40619. * AKA Glossiness in other nomenclature.
  40620. */
  40621. _this._microSurface = 0.9;
  40622. /**
  40623. * source material index of refraction (IOR)' / 'destination material IOR.
  40624. */
  40625. _this._indexOfRefraction = 0.66;
  40626. /**
  40627. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40628. */
  40629. _this._invertRefractionY = false;
  40630. /**
  40631. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40632. * Materials half opaque for instance using refraction could benefit from this control.
  40633. */
  40634. _this._linkRefractionWithTransparency = false;
  40635. /**
  40636. * Specifies that the material will use the light map as a show map.
  40637. */
  40638. _this._useLightmapAsShadowmap = false;
  40639. /**
  40640. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40641. * makes the reflect vector face the model (under horizon).
  40642. */
  40643. _this._useHorizonOcclusion = true;
  40644. /**
  40645. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40646. * too much the area relying on ambient texture to define their ambient occlusion.
  40647. */
  40648. _this._useRadianceOcclusion = true;
  40649. /**
  40650. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40651. */
  40652. _this._useAlphaFromAlbedoTexture = false;
  40653. /**
  40654. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40655. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40656. */
  40657. _this._useSpecularOverAlpha = true;
  40658. /**
  40659. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40660. */
  40661. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40662. /**
  40663. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40664. */
  40665. _this._useRoughnessFromMetallicTextureAlpha = true;
  40666. /**
  40667. * Specifies if the metallic texture contains the roughness information in its green channel.
  40668. */
  40669. _this._useRoughnessFromMetallicTextureGreen = false;
  40670. /**
  40671. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40672. */
  40673. _this._useMetallnessFromMetallicTextureBlue = false;
  40674. /**
  40675. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40676. */
  40677. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40678. /**
  40679. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40680. */
  40681. _this._useAmbientInGrayScale = false;
  40682. /**
  40683. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40684. * The material will try to infer what glossiness each pixel should be.
  40685. */
  40686. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40687. /**
  40688. * BJS is using an harcoded light falloff based on a manually sets up range.
  40689. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40690. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40691. */
  40692. _this._usePhysicalLightFalloff = true;
  40693. /**
  40694. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40695. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40696. */
  40697. _this._useRadianceOverAlpha = true;
  40698. /**
  40699. * Allows using an object space normal map (instead of tangent space).
  40700. */
  40701. _this._useObjectSpaceNormalMap = false;
  40702. /**
  40703. * Allows using the bump map in parallax mode.
  40704. */
  40705. _this._useParallax = false;
  40706. /**
  40707. * Allows using the bump map in parallax occlusion mode.
  40708. */
  40709. _this._useParallaxOcclusion = false;
  40710. /**
  40711. * Controls the scale bias of the parallax mode.
  40712. */
  40713. _this._parallaxScaleBias = 0.05;
  40714. /**
  40715. * If sets to true, disables all the lights affecting the material.
  40716. */
  40717. _this._disableLighting = false;
  40718. /**
  40719. * Number of Simultaneous lights allowed on the material.
  40720. */
  40721. _this._maxSimultaneousLights = 4;
  40722. /**
  40723. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40724. */
  40725. _this._invertNormalMapX = false;
  40726. /**
  40727. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40728. */
  40729. _this._invertNormalMapY = false;
  40730. /**
  40731. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40732. */
  40733. _this._twoSidedLighting = false;
  40734. /**
  40735. * Defines the alpha limits in alpha test mode.
  40736. */
  40737. _this._alphaCutOff = 0.4;
  40738. /**
  40739. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40740. */
  40741. _this._forceAlphaTest = false;
  40742. /**
  40743. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40744. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40745. */
  40746. _this._useAlphaFresnel = false;
  40747. /**
  40748. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40749. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40750. */
  40751. _this._useLinearAlphaFresnel = false;
  40752. /**
  40753. * The transparency mode of the material.
  40754. */
  40755. _this._transparencyMode = null;
  40756. /**
  40757. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40758. * from cos thetav and roughness:
  40759. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40760. */
  40761. _this._environmentBRDFTexture = null;
  40762. /**
  40763. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40764. */
  40765. _this._forceIrradianceInFragment = false;
  40766. /**
  40767. * Force normal to face away from face.
  40768. */
  40769. _this._forceNormalForward = false;
  40770. /**
  40771. * Stores the available render targets.
  40772. */
  40773. _this._renderTargets = new BABYLON.SmartArray(16);
  40774. /**
  40775. * Sets the global ambient color for the material used in lighting calculations.
  40776. */
  40777. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40778. // Setup the default processing configuration to the scene.
  40779. _this._attachImageProcessingConfiguration(null);
  40780. _this.getRenderTargetTextures = function () {
  40781. _this._renderTargets.reset();
  40782. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40783. _this._renderTargets.push(_this._reflectionTexture);
  40784. }
  40785. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40786. _this._renderTargets.push(_this._refractionTexture);
  40787. }
  40788. return _this._renderTargets;
  40789. };
  40790. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40791. return _this;
  40792. }
  40793. /**
  40794. * Attaches a new image processing configuration to the PBR Material.
  40795. * @param configuration
  40796. */
  40797. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40798. var _this = this;
  40799. if (configuration === this._imageProcessingConfiguration) {
  40800. return;
  40801. }
  40802. // Detaches observer.
  40803. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40804. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40805. }
  40806. // Pick the scene configuration if needed.
  40807. if (!configuration) {
  40808. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40809. }
  40810. else {
  40811. this._imageProcessingConfiguration = configuration;
  40812. }
  40813. // Attaches observer.
  40814. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40815. _this._markAllSubMeshesAsImageProcessingDirty();
  40816. });
  40817. };
  40818. /**
  40819. * Gets the name of the material class.
  40820. */
  40821. PBRBaseMaterial.prototype.getClassName = function () {
  40822. return "PBRBaseMaterial";
  40823. };
  40824. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40825. /**
  40826. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40827. */
  40828. get: function () {
  40829. return this._useLogarithmicDepth;
  40830. },
  40831. /**
  40832. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40833. */
  40834. set: function (value) {
  40835. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40836. },
  40837. enumerable: true,
  40838. configurable: true
  40839. });
  40840. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40841. /**
  40842. * Gets the current transparency mode.
  40843. */
  40844. get: function () {
  40845. return this._transparencyMode;
  40846. },
  40847. /**
  40848. * Sets the transparency mode of the material.
  40849. */
  40850. set: function (value) {
  40851. if (this._transparencyMode === value) {
  40852. return;
  40853. }
  40854. this._transparencyMode = value;
  40855. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40856. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40857. },
  40858. enumerable: true,
  40859. configurable: true
  40860. });
  40861. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40862. /**
  40863. * Returns true if alpha blending should be disabled.
  40864. */
  40865. get: function () {
  40866. return (this._linkRefractionWithTransparency ||
  40867. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40868. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40869. },
  40870. enumerable: true,
  40871. configurable: true
  40872. });
  40873. /**
  40874. * Specifies whether or not this material should be rendered in alpha blend mode.
  40875. */
  40876. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40877. if (this._disableAlphaBlending) {
  40878. return false;
  40879. }
  40880. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40881. };
  40882. /**
  40883. * Specifies if the mesh will require alpha blending.
  40884. * @param mesh - BJS mesh.
  40885. */
  40886. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40887. if (this._disableAlphaBlending) {
  40888. return false;
  40889. }
  40890. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40891. };
  40892. /**
  40893. * Specifies whether or not this material should be rendered in alpha test mode.
  40894. */
  40895. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40896. if (this._forceAlphaTest) {
  40897. return true;
  40898. }
  40899. if (this._linkRefractionWithTransparency) {
  40900. return false;
  40901. }
  40902. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40903. };
  40904. /**
  40905. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40906. */
  40907. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40908. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40909. };
  40910. /**
  40911. * Gets the texture used for the alpha test.
  40912. */
  40913. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40914. return this._albedoTexture;
  40915. };
  40916. /**
  40917. * Specifies that the submesh is ready to be used.
  40918. * @param mesh - BJS mesh.
  40919. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40920. * @param useInstances - Specifies that instances should be used.
  40921. * @returns - boolean indicating that the submesh is ready or not.
  40922. */
  40923. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40924. if (subMesh.effect && this.isFrozen) {
  40925. if (this._wasPreviouslyReady) {
  40926. return true;
  40927. }
  40928. }
  40929. if (!subMesh._materialDefines) {
  40930. subMesh._materialDefines = new PBRMaterialDefines();
  40931. }
  40932. var defines = subMesh._materialDefines;
  40933. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40934. if (defines._renderId === this.getScene().getRenderId()) {
  40935. return true;
  40936. }
  40937. }
  40938. var scene = this.getScene();
  40939. var engine = scene.getEngine();
  40940. if (defines._areTexturesDirty) {
  40941. if (scene.texturesEnabled) {
  40942. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40943. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40944. return false;
  40945. }
  40946. }
  40947. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40948. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40949. return false;
  40950. }
  40951. }
  40952. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40953. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40954. return false;
  40955. }
  40956. }
  40957. var reflectionTexture = this._getReflectionTexture();
  40958. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40959. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40960. return false;
  40961. }
  40962. }
  40963. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40964. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40965. return false;
  40966. }
  40967. }
  40968. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40969. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40970. return false;
  40971. }
  40972. }
  40973. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40974. if (this._metallicTexture) {
  40975. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40976. return false;
  40977. }
  40978. }
  40979. else if (this._reflectivityTexture) {
  40980. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40981. return false;
  40982. }
  40983. }
  40984. if (this._microSurfaceTexture) {
  40985. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40986. return false;
  40987. }
  40988. }
  40989. }
  40990. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40991. // Bump texture cannot be not blocking.
  40992. if (!this._bumpTexture.isReady()) {
  40993. return false;
  40994. }
  40995. }
  40996. var refractionTexture = this._getRefractionTexture();
  40997. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40998. if (!refractionTexture.isReadyOrNotBlocking()) {
  40999. return false;
  41000. }
  41001. }
  41002. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41003. // This is blocking.
  41004. if (!this._environmentBRDFTexture.isReady()) {
  41005. return false;
  41006. }
  41007. }
  41008. }
  41009. }
  41010. if (defines._areImageProcessingDirty) {
  41011. if (!this._imageProcessingConfiguration.isReady()) {
  41012. return false;
  41013. }
  41014. }
  41015. if (!engine.getCaps().standardDerivatives) {
  41016. var bufferMesh = null;
  41017. if (mesh.getClassName() === "InstancedMesh") {
  41018. bufferMesh = mesh.sourceMesh;
  41019. }
  41020. else if (mesh.getClassName() === "Mesh") {
  41021. bufferMesh = mesh;
  41022. }
  41023. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41024. bufferMesh.createNormals(true);
  41025. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41026. }
  41027. }
  41028. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41029. if (effect) {
  41030. scene.resetCachedMaterial();
  41031. subMesh.setEffect(effect, defines);
  41032. this.buildUniformLayout();
  41033. }
  41034. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41035. return false;
  41036. }
  41037. defines._renderId = scene.getRenderId();
  41038. this._wasPreviouslyReady = true;
  41039. return true;
  41040. };
  41041. /**
  41042. * Specifies if the material uses metallic roughness workflow.
  41043. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41044. */
  41045. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41046. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41047. return true;
  41048. }
  41049. return false;
  41050. };
  41051. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41052. if (onCompiled === void 0) { onCompiled = null; }
  41053. if (onError === void 0) { onError = null; }
  41054. if (useInstances === void 0) { useInstances = null; }
  41055. if (useClipPlane === void 0) { useClipPlane = null; }
  41056. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41057. if (!defines.isDirty) {
  41058. return null;
  41059. }
  41060. defines.markAsProcessed();
  41061. var scene = this.getScene();
  41062. var engine = scene.getEngine();
  41063. // Fallbacks
  41064. var fallbacks = new BABYLON.EffectFallbacks();
  41065. var fallbackRank = 0;
  41066. if (defines.USESPHERICALINVERTEX) {
  41067. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41068. }
  41069. if (defines.FOG) {
  41070. fallbacks.addFallback(fallbackRank, "FOG");
  41071. }
  41072. if (defines.POINTSIZE) {
  41073. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41074. }
  41075. if (defines.LOGARITHMICDEPTH) {
  41076. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41077. }
  41078. if (defines.PARALLAX) {
  41079. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41080. }
  41081. if (defines.PARALLAXOCCLUSION) {
  41082. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41083. }
  41084. if (defines.ENVIRONMENTBRDF) {
  41085. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41086. }
  41087. if (defines.TANGENT) {
  41088. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41089. }
  41090. if (defines.BUMP) {
  41091. fallbacks.addFallback(fallbackRank++, "BUMP");
  41092. }
  41093. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41094. if (defines.SPECULARTERM) {
  41095. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41096. }
  41097. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41098. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41099. }
  41100. if (defines.LIGHTMAP) {
  41101. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41102. }
  41103. if (defines.NORMAL) {
  41104. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41105. }
  41106. if (defines.AMBIENT) {
  41107. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41108. }
  41109. if (defines.EMISSIVE) {
  41110. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41111. }
  41112. if (defines.VERTEXCOLOR) {
  41113. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41114. }
  41115. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41116. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41117. }
  41118. if (defines.MORPHTARGETS) {
  41119. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41120. }
  41121. //Attributes
  41122. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41123. if (defines.NORMAL) {
  41124. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41125. }
  41126. if (defines.TANGENT) {
  41127. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41128. }
  41129. if (defines.UV1) {
  41130. attribs.push(BABYLON.VertexBuffer.UVKind);
  41131. }
  41132. if (defines.UV2) {
  41133. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41134. }
  41135. if (defines.VERTEXCOLOR) {
  41136. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41137. }
  41138. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41139. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41140. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41141. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41142. "vFogInfos", "vFogColor", "pointSize",
  41143. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41144. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41145. "mBones",
  41146. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41147. "vLightingIntensity",
  41148. "logarithmicDepthConstant",
  41149. "vSphericalX", "vSphericalY", "vSphericalZ",
  41150. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41151. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41152. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41153. "vTangentSpaceParams"
  41154. ];
  41155. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41156. "bumpSampler", "lightmapSampler", "opacitySampler",
  41157. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41158. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41159. "microSurfaceSampler", "environmentBrdfSampler"];
  41160. var uniformBuffers = ["Material", "Scene"];
  41161. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41162. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41163. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41164. uniformsNames: uniforms,
  41165. uniformBuffersNames: uniformBuffers,
  41166. samplers: samplers,
  41167. defines: defines,
  41168. maxSimultaneousLights: this._maxSimultaneousLights
  41169. });
  41170. var join = defines.toString();
  41171. return engine.createEffect("pbr", {
  41172. attributes: attribs,
  41173. uniformsNames: uniforms,
  41174. uniformBuffersNames: uniformBuffers,
  41175. samplers: samplers,
  41176. defines: join,
  41177. fallbacks: fallbacks,
  41178. onCompiled: onCompiled,
  41179. onError: onError,
  41180. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41181. }, engine);
  41182. };
  41183. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41184. if (useInstances === void 0) { useInstances = null; }
  41185. if (useClipPlane === void 0) { useClipPlane = null; }
  41186. var scene = this.getScene();
  41187. var engine = scene.getEngine();
  41188. // Lights
  41189. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41190. defines._needNormals = true;
  41191. // Textures
  41192. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41193. if (defines._areTexturesDirty) {
  41194. defines._needUVs = false;
  41195. if (scene.texturesEnabled) {
  41196. if (scene.getEngine().getCaps().textureLOD) {
  41197. defines.LODBASEDMICROSFURACE = true;
  41198. }
  41199. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41201. }
  41202. else {
  41203. defines.ALBEDO = false;
  41204. }
  41205. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41207. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41208. }
  41209. else {
  41210. defines.AMBIENT = false;
  41211. }
  41212. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41213. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41214. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41215. }
  41216. else {
  41217. defines.OPACITY = false;
  41218. }
  41219. var reflectionTexture = this._getReflectionTexture();
  41220. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41221. defines.REFLECTION = true;
  41222. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41223. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41224. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41225. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41226. defines.INVERTCUBICMAP = true;
  41227. }
  41228. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41229. switch (reflectionTexture.coordinatesMode) {
  41230. case BABYLON.Texture.CUBIC_MODE:
  41231. case BABYLON.Texture.INVCUBIC_MODE:
  41232. defines.REFLECTIONMAP_CUBIC = true;
  41233. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41234. break;
  41235. case BABYLON.Texture.EXPLICIT_MODE:
  41236. defines.REFLECTIONMAP_EXPLICIT = true;
  41237. break;
  41238. case BABYLON.Texture.PLANAR_MODE:
  41239. defines.REFLECTIONMAP_PLANAR = true;
  41240. break;
  41241. case BABYLON.Texture.PROJECTION_MODE:
  41242. defines.REFLECTIONMAP_PROJECTION = true;
  41243. break;
  41244. case BABYLON.Texture.SKYBOX_MODE:
  41245. defines.REFLECTIONMAP_SKYBOX = true;
  41246. break;
  41247. case BABYLON.Texture.SPHERICAL_MODE:
  41248. defines.REFLECTIONMAP_SPHERICAL = true;
  41249. break;
  41250. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41251. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41252. break;
  41253. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41254. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41255. break;
  41256. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41257. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41258. break;
  41259. }
  41260. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41261. if (reflectionTexture.sphericalPolynomial) {
  41262. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41263. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41264. defines.USESPHERICALINVERTEX = false;
  41265. }
  41266. else {
  41267. defines.USESPHERICALINVERTEX = true;
  41268. }
  41269. }
  41270. }
  41271. }
  41272. else {
  41273. defines.REFLECTION = false;
  41274. defines.REFLECTIONMAP_3D = false;
  41275. defines.REFLECTIONMAP_SPHERICAL = false;
  41276. defines.REFLECTIONMAP_PLANAR = false;
  41277. defines.REFLECTIONMAP_CUBIC = false;
  41278. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41279. defines.REFLECTIONMAP_PROJECTION = false;
  41280. defines.REFLECTIONMAP_SKYBOX = false;
  41281. defines.REFLECTIONMAP_EXPLICIT = false;
  41282. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41283. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41284. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41285. defines.INVERTCUBICMAP = false;
  41286. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41287. defines.USESPHERICALINVERTEX = false;
  41288. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41289. defines.LODINREFLECTIONALPHA = false;
  41290. defines.GAMMAREFLECTION = false;
  41291. }
  41292. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41294. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41295. }
  41296. else {
  41297. defines.LIGHTMAP = false;
  41298. }
  41299. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41301. }
  41302. else {
  41303. defines.EMISSIVE = false;
  41304. }
  41305. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41306. if (this._metallicTexture) {
  41307. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41308. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41309. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41310. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41311. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41312. }
  41313. else if (this._reflectivityTexture) {
  41314. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41315. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41316. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41317. }
  41318. else {
  41319. defines.REFLECTIVITY = false;
  41320. }
  41321. if (this._microSurfaceTexture) {
  41322. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41323. }
  41324. else {
  41325. defines.MICROSURFACEMAP = false;
  41326. }
  41327. }
  41328. else {
  41329. defines.REFLECTIVITY = false;
  41330. defines.MICROSURFACEMAP = false;
  41331. }
  41332. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41333. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41334. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41335. defines.PARALLAX = true;
  41336. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41337. }
  41338. else {
  41339. defines.PARALLAX = false;
  41340. }
  41341. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41342. }
  41343. else {
  41344. defines.BUMP = false;
  41345. }
  41346. var refractionTexture = this._getRefractionTexture();
  41347. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41348. defines.REFRACTION = true;
  41349. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41350. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41351. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41352. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41353. if (this._linkRefractionWithTransparency) {
  41354. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41355. }
  41356. }
  41357. else {
  41358. defines.REFRACTION = false;
  41359. }
  41360. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41361. defines.ENVIRONMENTBRDF = true;
  41362. }
  41363. else {
  41364. defines.ENVIRONMENTBRDF = false;
  41365. }
  41366. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41367. defines.ALPHAFROMALBEDO = true;
  41368. }
  41369. else {
  41370. defines.ALPHAFROMALBEDO = false;
  41371. }
  41372. }
  41373. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41374. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41375. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41376. if (!this.backFaceCulling && this._twoSidedLighting) {
  41377. defines.TWOSIDEDLIGHTING = true;
  41378. }
  41379. else {
  41380. defines.TWOSIDEDLIGHTING = false;
  41381. }
  41382. defines.ALPHATESTVALUE = this._alphaCutOff;
  41383. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41384. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41385. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41386. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41387. }
  41388. if (defines._areImageProcessingDirty) {
  41389. this._imageProcessingConfiguration.prepareDefines(defines);
  41390. }
  41391. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41392. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41393. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41394. // Misc.
  41395. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41396. // Values that need to be evaluated on every frame
  41397. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41398. // Attribs
  41399. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41400. };
  41401. /**
  41402. * Force shader compilation
  41403. */
  41404. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41405. var _this = this;
  41406. var localOptions = __assign({ clipPlane: false }, options);
  41407. var defines = new PBRMaterialDefines();
  41408. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41409. if (effect.isReady()) {
  41410. if (onCompiled) {
  41411. onCompiled(this);
  41412. }
  41413. }
  41414. else {
  41415. effect.onCompileObservable.add(function () {
  41416. if (onCompiled) {
  41417. onCompiled(_this);
  41418. }
  41419. });
  41420. }
  41421. };
  41422. /**
  41423. * Initializes the uniform buffer layout for the shader.
  41424. */
  41425. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41426. // Order is important !
  41427. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41428. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41429. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41430. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41431. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41432. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41433. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41434. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41435. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41436. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41437. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41438. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41439. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41440. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41441. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41442. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41443. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41444. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41445. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41446. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41447. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41448. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41449. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41450. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41451. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41452. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41453. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41454. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41455. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41456. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41457. this._uniformBuffer.addUniform("pointSize", 1);
  41458. this._uniformBuffer.create();
  41459. };
  41460. /**
  41461. * Unbinds the textures.
  41462. */
  41463. PBRBaseMaterial.prototype.unbind = function () {
  41464. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41465. this._uniformBuffer.setTexture("reflectionSampler", null);
  41466. }
  41467. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41468. this._uniformBuffer.setTexture("refractionSampler", null);
  41469. }
  41470. _super.prototype.unbind.call(this);
  41471. };
  41472. /**
  41473. * Binds the submesh data.
  41474. * @param world - The world matrix.
  41475. * @param mesh - The BJS mesh.
  41476. * @param subMesh - A submesh of the BJS mesh.
  41477. */
  41478. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41479. var scene = this.getScene();
  41480. var defines = subMesh._materialDefines;
  41481. if (!defines) {
  41482. return;
  41483. }
  41484. var effect = subMesh.effect;
  41485. if (!effect) {
  41486. return;
  41487. }
  41488. this._activeEffect = effect;
  41489. // Matrices
  41490. this.bindOnlyWorldMatrix(world);
  41491. // Normal Matrix
  41492. if (defines.OBJECTSPACE_NORMALMAP) {
  41493. world.toNormalMatrix(this._normalMatrix);
  41494. this.bindOnlyNormalMatrix(this._normalMatrix);
  41495. }
  41496. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41497. // Bones
  41498. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41499. var reflectionTexture = null;
  41500. if (mustRebind) {
  41501. this._uniformBuffer.bindToEffect(effect, "Material");
  41502. this.bindViewProjection(effect);
  41503. reflectionTexture = this._getReflectionTexture();
  41504. var refractionTexture = this._getRefractionTexture();
  41505. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41506. // Texture uniforms
  41507. if (scene.texturesEnabled) {
  41508. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41509. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41510. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41511. }
  41512. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41513. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41514. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41515. }
  41516. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41517. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41518. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41519. }
  41520. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41521. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41522. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41523. if (reflectionTexture.boundingBoxSize) {
  41524. var cubeTexture = reflectionTexture;
  41525. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41526. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41527. }
  41528. var polynomials = reflectionTexture.sphericalPolynomial;
  41529. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41530. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41531. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41532. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41533. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41534. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41535. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41536. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41537. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41538. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41539. }
  41540. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41541. }
  41542. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41543. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41544. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41545. }
  41546. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41547. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41548. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41549. }
  41550. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41551. if (this._metallicTexture) {
  41552. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41553. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41554. }
  41555. else if (this._reflectivityTexture) {
  41556. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41557. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41558. }
  41559. if (this._microSurfaceTexture) {
  41560. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41561. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41562. }
  41563. }
  41564. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41565. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41566. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41567. if (scene._mirroredCameraPosition) {
  41568. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41569. }
  41570. else {
  41571. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41572. }
  41573. }
  41574. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41575. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41576. var depth = 1.0;
  41577. if (!refractionTexture.isCube) {
  41578. if (refractionTexture.depth) {
  41579. depth = refractionTexture.depth;
  41580. }
  41581. }
  41582. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41583. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41584. }
  41585. }
  41586. // Point size
  41587. if (this.pointsCloud) {
  41588. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41589. }
  41590. // Colors
  41591. if (defines.METALLICWORKFLOW) {
  41592. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41593. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41594. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41595. }
  41596. else {
  41597. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41598. }
  41599. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41600. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41601. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41602. // Misc
  41603. this._lightingInfos.x = this._directIntensity;
  41604. this._lightingInfos.y = this._emissiveIntensity;
  41605. this._lightingInfos.z = this._environmentIntensity;
  41606. this._lightingInfos.w = this._specularIntensity;
  41607. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41608. }
  41609. // Textures
  41610. if (scene.texturesEnabled) {
  41611. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41612. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41613. }
  41614. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41615. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41616. }
  41617. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41618. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41619. }
  41620. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41621. if (defines.LODBASEDMICROSFURACE) {
  41622. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41623. }
  41624. else {
  41625. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41626. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41627. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41628. }
  41629. }
  41630. if (defines.ENVIRONMENTBRDF) {
  41631. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41632. }
  41633. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41634. if (defines.LODBASEDMICROSFURACE) {
  41635. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41636. }
  41637. else {
  41638. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41639. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41640. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41641. }
  41642. }
  41643. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41644. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41645. }
  41646. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41647. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41648. }
  41649. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41650. if (this._metallicTexture) {
  41651. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41652. }
  41653. else if (this._reflectivityTexture) {
  41654. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41655. }
  41656. if (this._microSurfaceTexture) {
  41657. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41658. }
  41659. }
  41660. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41661. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41662. }
  41663. }
  41664. // Clip plane
  41665. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41666. // Colors
  41667. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41668. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41669. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41670. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41671. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41672. }
  41673. if (mustRebind || !this.isFrozen) {
  41674. // Lights
  41675. if (scene.lightsEnabled && !this._disableLighting) {
  41676. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41677. }
  41678. // View
  41679. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41680. this.bindView(effect);
  41681. }
  41682. // Fog
  41683. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41684. // Morph targets
  41685. if (defines.NUM_MORPH_INFLUENCERS) {
  41686. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41687. }
  41688. // image processing
  41689. this._imageProcessingConfiguration.bind(this._activeEffect);
  41690. // Log. depth
  41691. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41692. }
  41693. this._uniformBuffer.update();
  41694. this._afterBind(mesh);
  41695. };
  41696. /**
  41697. * Returns the animatable textures.
  41698. * @returns - Array of animatable textures.
  41699. */
  41700. PBRBaseMaterial.prototype.getAnimatables = function () {
  41701. var results = [];
  41702. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41703. results.push(this._albedoTexture);
  41704. }
  41705. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41706. results.push(this._ambientTexture);
  41707. }
  41708. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41709. results.push(this._opacityTexture);
  41710. }
  41711. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41712. results.push(this._reflectionTexture);
  41713. }
  41714. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41715. results.push(this._emissiveTexture);
  41716. }
  41717. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41718. results.push(this._metallicTexture);
  41719. }
  41720. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41721. results.push(this._reflectivityTexture);
  41722. }
  41723. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41724. results.push(this._bumpTexture);
  41725. }
  41726. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41727. results.push(this._lightmapTexture);
  41728. }
  41729. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41730. results.push(this._refractionTexture);
  41731. }
  41732. return results;
  41733. };
  41734. /**
  41735. * Returns the texture used for reflections.
  41736. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41737. */
  41738. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41739. if (this._reflectionTexture) {
  41740. return this._reflectionTexture;
  41741. }
  41742. return this.getScene().environmentTexture;
  41743. };
  41744. /**
  41745. * Returns the texture used for refraction or null if none is used.
  41746. * @returns - Refection texture if present. If no refraction texture and refraction
  41747. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41748. */
  41749. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41750. if (this._refractionTexture) {
  41751. return this._refractionTexture;
  41752. }
  41753. if (this._linkRefractionWithTransparency) {
  41754. return this.getScene().environmentTexture;
  41755. }
  41756. return null;
  41757. };
  41758. /**
  41759. * Disposes the resources of the material.
  41760. * @param forceDisposeEffect - Forces the disposal of effects.
  41761. * @param forceDisposeTextures - Forces the disposal of all textures.
  41762. */
  41763. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41764. if (forceDisposeTextures) {
  41765. if (this._albedoTexture) {
  41766. this._albedoTexture.dispose();
  41767. }
  41768. if (this._ambientTexture) {
  41769. this._ambientTexture.dispose();
  41770. }
  41771. if (this._opacityTexture) {
  41772. this._opacityTexture.dispose();
  41773. }
  41774. if (this._reflectionTexture) {
  41775. this._reflectionTexture.dispose();
  41776. }
  41777. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41778. this._environmentBRDFTexture.dispose();
  41779. }
  41780. if (this._emissiveTexture) {
  41781. this._emissiveTexture.dispose();
  41782. }
  41783. if (this._metallicTexture) {
  41784. this._metallicTexture.dispose();
  41785. }
  41786. if (this._reflectivityTexture) {
  41787. this._reflectivityTexture.dispose();
  41788. }
  41789. if (this._bumpTexture) {
  41790. this._bumpTexture.dispose();
  41791. }
  41792. if (this._lightmapTexture) {
  41793. this._lightmapTexture.dispose();
  41794. }
  41795. if (this._refractionTexture) {
  41796. this._refractionTexture.dispose();
  41797. }
  41798. }
  41799. this._renderTargets.dispose();
  41800. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41801. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41802. }
  41803. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41804. };
  41805. /**
  41806. * Stores the reflectivity values based on metallic roughness workflow.
  41807. */
  41808. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41809. __decorate([
  41810. BABYLON.serializeAsImageProcessingConfiguration()
  41811. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41812. __decorate([
  41813. BABYLON.serialize()
  41814. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41815. __decorate([
  41816. BABYLON.serialize()
  41817. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41818. return PBRBaseMaterial;
  41819. }(BABYLON.PushMaterial));
  41820. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41821. })(BABYLON || (BABYLON = {}));
  41822. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41823. var BABYLON;
  41824. (function (BABYLON) {
  41825. /**
  41826. * The Physically based simple base material of BJS.
  41827. *
  41828. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41829. * It is used as the base class for both the specGloss and metalRough conventions.
  41830. */
  41831. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41832. __extends(PBRBaseSimpleMaterial, _super);
  41833. /**
  41834. * Instantiates a new PBRMaterial instance.
  41835. *
  41836. * @param name The material name
  41837. * @param scene The scene the material will be use in.
  41838. */
  41839. function PBRBaseSimpleMaterial(name, scene) {
  41840. var _this = _super.call(this, name, scene) || this;
  41841. /**
  41842. * Number of Simultaneous lights allowed on the material.
  41843. */
  41844. _this.maxSimultaneousLights = 4;
  41845. /**
  41846. * If sets to true, disables all the lights affecting the material.
  41847. */
  41848. _this.disableLighting = false;
  41849. /**
  41850. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41851. */
  41852. _this.invertNormalMapX = false;
  41853. /**
  41854. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41855. */
  41856. _this.invertNormalMapY = false;
  41857. /**
  41858. * Emissivie color used to self-illuminate the model.
  41859. */
  41860. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41861. /**
  41862. * Occlusion Channel Strenght.
  41863. */
  41864. _this.occlusionStrength = 1.0;
  41865. _this.useLightmapAsShadowmap = false;
  41866. _this._useAlphaFromAlbedoTexture = true;
  41867. _this._useAmbientInGrayScale = true;
  41868. return _this;
  41869. }
  41870. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41871. /**
  41872. * Gets the current double sided mode.
  41873. */
  41874. get: function () {
  41875. return this._twoSidedLighting;
  41876. },
  41877. /**
  41878. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41879. */
  41880. set: function (value) {
  41881. if (this._twoSidedLighting === value) {
  41882. return;
  41883. }
  41884. this._twoSidedLighting = value;
  41885. this.backFaceCulling = !value;
  41886. this._markAllSubMeshesAsTexturesDirty();
  41887. },
  41888. enumerable: true,
  41889. configurable: true
  41890. });
  41891. /**
  41892. * Return the active textures of the material.
  41893. */
  41894. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41895. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41896. if (this.environmentTexture) {
  41897. activeTextures.push(this.environmentTexture);
  41898. }
  41899. if (this.normalTexture) {
  41900. activeTextures.push(this.normalTexture);
  41901. }
  41902. if (this.emissiveTexture) {
  41903. activeTextures.push(this.emissiveTexture);
  41904. }
  41905. if (this.occlusionTexture) {
  41906. activeTextures.push(this.occlusionTexture);
  41907. }
  41908. if (this.lightmapTexture) {
  41909. activeTextures.push(this.lightmapTexture);
  41910. }
  41911. return activeTextures;
  41912. };
  41913. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41914. if (_super.prototype.hasTexture.call(this, texture)) {
  41915. return true;
  41916. }
  41917. if (this.lightmapTexture === texture) {
  41918. return true;
  41919. }
  41920. return false;
  41921. };
  41922. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41923. return "PBRBaseSimpleMaterial";
  41924. };
  41925. __decorate([
  41926. BABYLON.serialize(),
  41927. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41928. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41929. __decorate([
  41930. BABYLON.serialize(),
  41931. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41932. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41933. __decorate([
  41934. BABYLON.serializeAsTexture(),
  41935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41936. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41937. __decorate([
  41938. BABYLON.serialize(),
  41939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41940. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41941. __decorate([
  41942. BABYLON.serialize(),
  41943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41944. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41945. __decorate([
  41946. BABYLON.serializeAsTexture(),
  41947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41948. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41949. __decorate([
  41950. BABYLON.serializeAsColor3("emissive"),
  41951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41952. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41953. __decorate([
  41954. BABYLON.serializeAsTexture(),
  41955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41956. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41957. __decorate([
  41958. BABYLON.serialize(),
  41959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41960. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41961. __decorate([
  41962. BABYLON.serializeAsTexture(),
  41963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41964. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41965. __decorate([
  41966. BABYLON.serialize(),
  41967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41968. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41969. __decorate([
  41970. BABYLON.serialize()
  41971. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41972. __decorate([
  41973. BABYLON.serializeAsTexture(),
  41974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41975. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41976. __decorate([
  41977. BABYLON.serialize(),
  41978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41979. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41980. return PBRBaseSimpleMaterial;
  41981. }(BABYLON.PBRBaseMaterial));
  41982. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41983. })(BABYLON || (BABYLON = {}));
  41984. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41985. var BABYLON;
  41986. (function (BABYLON) {
  41987. /**
  41988. * The Physically based material of BJS.
  41989. *
  41990. * This offers the main features of a standard PBR material.
  41991. * For more information, please refer to the documentation :
  41992. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41993. */
  41994. var PBRMaterial = /** @class */ (function (_super) {
  41995. __extends(PBRMaterial, _super);
  41996. /**
  41997. * Instantiates a new PBRMaterial instance.
  41998. *
  41999. * @param name The material name
  42000. * @param scene The scene the material will be use in.
  42001. */
  42002. function PBRMaterial(name, scene) {
  42003. var _this = _super.call(this, name, scene) || this;
  42004. /**
  42005. * Intensity of the direct lights e.g. the four lights available in your scene.
  42006. * This impacts both the direct diffuse and specular highlights.
  42007. */
  42008. _this.directIntensity = 1.0;
  42009. /**
  42010. * Intensity of the emissive part of the material.
  42011. * This helps controlling the emissive effect without modifying the emissive color.
  42012. */
  42013. _this.emissiveIntensity = 1.0;
  42014. /**
  42015. * Intensity of the environment e.g. how much the environment will light the object
  42016. * either through harmonics for rough material or through the refelction for shiny ones.
  42017. */
  42018. _this.environmentIntensity = 1.0;
  42019. /**
  42020. * This is a special control allowing the reduction of the specular highlights coming from the
  42021. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42022. */
  42023. _this.specularIntensity = 1.0;
  42024. /**
  42025. * Debug Control allowing disabling the bump map on this material.
  42026. */
  42027. _this.disableBumpMap = false;
  42028. /**
  42029. * AKA Occlusion Texture Intensity in other nomenclature.
  42030. */
  42031. _this.ambientTextureStrength = 1.0;
  42032. /**
  42033. * The color of a material in ambient lighting.
  42034. */
  42035. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42036. /**
  42037. * AKA Diffuse Color in other nomenclature.
  42038. */
  42039. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42040. /**
  42041. * AKA Specular Color in other nomenclature.
  42042. */
  42043. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42044. /**
  42045. * The color reflected from the material.
  42046. */
  42047. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42048. /**
  42049. * The color emitted from the material.
  42050. */
  42051. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42052. /**
  42053. * AKA Glossiness in other nomenclature.
  42054. */
  42055. _this.microSurface = 1.0;
  42056. /**
  42057. * source material index of refraction (IOR)' / 'destination material IOR.
  42058. */
  42059. _this.indexOfRefraction = 0.66;
  42060. /**
  42061. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42062. */
  42063. _this.invertRefractionY = false;
  42064. /**
  42065. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42066. * Materials half opaque for instance using refraction could benefit from this control.
  42067. */
  42068. _this.linkRefractionWithTransparency = false;
  42069. _this.useLightmapAsShadowmap = false;
  42070. /**
  42071. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42072. */
  42073. _this.useAlphaFromAlbedoTexture = false;
  42074. /**
  42075. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42076. */
  42077. _this.forceAlphaTest = false;
  42078. /**
  42079. * Defines the alpha limits in alpha test mode.
  42080. */
  42081. _this.alphaCutOff = 0.4;
  42082. /**
  42083. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42084. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42085. */
  42086. _this.useSpecularOverAlpha = true;
  42087. /**
  42088. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42089. */
  42090. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42091. /**
  42092. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42093. */
  42094. _this.useRoughnessFromMetallicTextureAlpha = true;
  42095. /**
  42096. * Specifies if the metallic texture contains the roughness information in its green channel.
  42097. */
  42098. _this.useRoughnessFromMetallicTextureGreen = false;
  42099. /**
  42100. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42101. */
  42102. _this.useMetallnessFromMetallicTextureBlue = false;
  42103. /**
  42104. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42105. */
  42106. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42107. /**
  42108. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42109. */
  42110. _this.useAmbientInGrayScale = false;
  42111. /**
  42112. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42113. * The material will try to infer what glossiness each pixel should be.
  42114. */
  42115. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42116. /**
  42117. * BJS is using an harcoded light falloff based on a manually sets up range.
  42118. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42119. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42120. */
  42121. _this.usePhysicalLightFalloff = true;
  42122. /**
  42123. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42124. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42125. */
  42126. _this.useRadianceOverAlpha = true;
  42127. /**
  42128. * Allows using an object space normal map (instead of tangent space).
  42129. */
  42130. _this.useObjectSpaceNormalMap = false;
  42131. /**
  42132. * Allows using the bump map in parallax mode.
  42133. */
  42134. _this.useParallax = false;
  42135. /**
  42136. * Allows using the bump map in parallax occlusion mode.
  42137. */
  42138. _this.useParallaxOcclusion = false;
  42139. /**
  42140. * Controls the scale bias of the parallax mode.
  42141. */
  42142. _this.parallaxScaleBias = 0.05;
  42143. /**
  42144. * If sets to true, disables all the lights affecting the material.
  42145. */
  42146. _this.disableLighting = false;
  42147. /**
  42148. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42149. */
  42150. _this.forceIrradianceInFragment = false;
  42151. /**
  42152. * Number of Simultaneous lights allowed on the material.
  42153. */
  42154. _this.maxSimultaneousLights = 4;
  42155. /**
  42156. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42157. */
  42158. _this.invertNormalMapX = false;
  42159. /**
  42160. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42161. */
  42162. _this.invertNormalMapY = false;
  42163. /**
  42164. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42165. */
  42166. _this.twoSidedLighting = false;
  42167. /**
  42168. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42169. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42170. */
  42171. _this.useAlphaFresnel = false;
  42172. /**
  42173. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42174. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42175. */
  42176. _this.useLinearAlphaFresnel = false;
  42177. /**
  42178. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42179. * And/Or occlude the blended part.
  42180. */
  42181. _this.environmentBRDFTexture = null;
  42182. /**
  42183. * Force normal to face away from face.
  42184. */
  42185. _this.forceNormalForward = false;
  42186. /**
  42187. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42188. * makes the reflect vector face the model (under horizon).
  42189. */
  42190. _this.useHorizonOcclusion = true;
  42191. /**
  42192. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42193. * too much the area relying on ambient texture to define their ambient occlusion.
  42194. */
  42195. _this.useRadianceOcclusion = true;
  42196. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42197. return _this;
  42198. }
  42199. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42200. /**
  42201. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42202. */
  42203. get: function () {
  42204. return this._PBRMATERIAL_OPAQUE;
  42205. },
  42206. enumerable: true,
  42207. configurable: true
  42208. });
  42209. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42210. /**
  42211. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42212. */
  42213. get: function () {
  42214. return this._PBRMATERIAL_ALPHATEST;
  42215. },
  42216. enumerable: true,
  42217. configurable: true
  42218. });
  42219. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42220. /**
  42221. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42222. */
  42223. get: function () {
  42224. return this._PBRMATERIAL_ALPHABLEND;
  42225. },
  42226. enumerable: true,
  42227. configurable: true
  42228. });
  42229. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42230. /**
  42231. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42232. * They are also discarded below the alpha cutoff threshold to improve performances.
  42233. */
  42234. get: function () {
  42235. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42236. },
  42237. enumerable: true,
  42238. configurable: true
  42239. });
  42240. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42241. /**
  42242. * Gets the image processing configuration used either in this material.
  42243. */
  42244. get: function () {
  42245. return this._imageProcessingConfiguration;
  42246. },
  42247. /**
  42248. * Sets the Default image processing configuration used either in the this material.
  42249. *
  42250. * If sets to null, the scene one is in use.
  42251. */
  42252. set: function (value) {
  42253. this._attachImageProcessingConfiguration(value);
  42254. // Ensure the effect will be rebuilt.
  42255. this._markAllSubMeshesAsTexturesDirty();
  42256. },
  42257. enumerable: true,
  42258. configurable: true
  42259. });
  42260. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42261. /**
  42262. * Gets wether the color curves effect is enabled.
  42263. */
  42264. get: function () {
  42265. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42266. },
  42267. /**
  42268. * Sets wether the color curves effect is enabled.
  42269. */
  42270. set: function (value) {
  42271. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42272. },
  42273. enumerable: true,
  42274. configurable: true
  42275. });
  42276. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42277. /**
  42278. * Gets wether the color grading effect is enabled.
  42279. */
  42280. get: function () {
  42281. return this.imageProcessingConfiguration.colorGradingEnabled;
  42282. },
  42283. /**
  42284. * Gets wether the color grading effect is enabled.
  42285. */
  42286. set: function (value) {
  42287. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42288. },
  42289. enumerable: true,
  42290. configurable: true
  42291. });
  42292. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42293. /**
  42294. * Gets wether tonemapping is enabled or not.
  42295. */
  42296. get: function () {
  42297. return this._imageProcessingConfiguration.toneMappingEnabled;
  42298. },
  42299. /**
  42300. * Sets wether tonemapping is enabled or not
  42301. */
  42302. set: function (value) {
  42303. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42304. },
  42305. enumerable: true,
  42306. configurable: true
  42307. });
  42308. ;
  42309. ;
  42310. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42311. /**
  42312. * The camera exposure used on this material.
  42313. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42314. * This corresponds to a photographic exposure.
  42315. */
  42316. get: function () {
  42317. return this._imageProcessingConfiguration.exposure;
  42318. },
  42319. /**
  42320. * The camera exposure used on this material.
  42321. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42322. * This corresponds to a photographic exposure.
  42323. */
  42324. set: function (value) {
  42325. this._imageProcessingConfiguration.exposure = value;
  42326. },
  42327. enumerable: true,
  42328. configurable: true
  42329. });
  42330. ;
  42331. ;
  42332. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42333. /**
  42334. * Gets The camera contrast used on this material.
  42335. */
  42336. get: function () {
  42337. return this._imageProcessingConfiguration.contrast;
  42338. },
  42339. /**
  42340. * Sets The camera contrast used on this material.
  42341. */
  42342. set: function (value) {
  42343. this._imageProcessingConfiguration.contrast = value;
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42349. /**
  42350. * Gets the Color Grading 2D Lookup Texture.
  42351. */
  42352. get: function () {
  42353. return this._imageProcessingConfiguration.colorGradingTexture;
  42354. },
  42355. /**
  42356. * Sets the Color Grading 2D Lookup Texture.
  42357. */
  42358. set: function (value) {
  42359. this._imageProcessingConfiguration.colorGradingTexture = value;
  42360. },
  42361. enumerable: true,
  42362. configurable: true
  42363. });
  42364. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42365. /**
  42366. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42367. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42368. * 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;
  42369. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42370. */
  42371. get: function () {
  42372. return this._imageProcessingConfiguration.colorCurves;
  42373. },
  42374. /**
  42375. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42376. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42377. * 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;
  42378. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42379. */
  42380. set: function (value) {
  42381. this._imageProcessingConfiguration.colorCurves = value;
  42382. },
  42383. enumerable: true,
  42384. configurable: true
  42385. });
  42386. /**
  42387. * Returns the name of this material class.
  42388. */
  42389. PBRMaterial.prototype.getClassName = function () {
  42390. return "PBRMaterial";
  42391. };
  42392. /**
  42393. * Returns an array of the actively used textures.
  42394. * @returns - Array of BaseTextures
  42395. */
  42396. PBRMaterial.prototype.getActiveTextures = function () {
  42397. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42398. if (this._albedoTexture) {
  42399. activeTextures.push(this._albedoTexture);
  42400. }
  42401. if (this._ambientTexture) {
  42402. activeTextures.push(this._ambientTexture);
  42403. }
  42404. if (this._opacityTexture) {
  42405. activeTextures.push(this._opacityTexture);
  42406. }
  42407. if (this._reflectionTexture) {
  42408. activeTextures.push(this._reflectionTexture);
  42409. }
  42410. if (this._emissiveTexture) {
  42411. activeTextures.push(this._emissiveTexture);
  42412. }
  42413. if (this._reflectivityTexture) {
  42414. activeTextures.push(this._reflectivityTexture);
  42415. }
  42416. if (this._metallicTexture) {
  42417. activeTextures.push(this._metallicTexture);
  42418. }
  42419. if (this._microSurfaceTexture) {
  42420. activeTextures.push(this._microSurfaceTexture);
  42421. }
  42422. if (this._bumpTexture) {
  42423. activeTextures.push(this._bumpTexture);
  42424. }
  42425. if (this._lightmapTexture) {
  42426. activeTextures.push(this._lightmapTexture);
  42427. }
  42428. if (this._refractionTexture) {
  42429. activeTextures.push(this._refractionTexture);
  42430. }
  42431. return activeTextures;
  42432. };
  42433. /**
  42434. * Checks to see if a texture is used in the material.
  42435. * @param texture - Base texture to use.
  42436. * @returns - Boolean specifying if a texture is used in the material.
  42437. */
  42438. PBRMaterial.prototype.hasTexture = function (texture) {
  42439. if (_super.prototype.hasTexture.call(this, texture)) {
  42440. return true;
  42441. }
  42442. if (this._albedoTexture === texture) {
  42443. return true;
  42444. }
  42445. if (this._ambientTexture === texture) {
  42446. return true;
  42447. }
  42448. if (this._opacityTexture === texture) {
  42449. return true;
  42450. }
  42451. if (this._reflectionTexture === texture) {
  42452. return true;
  42453. }
  42454. if (this._reflectivityTexture === texture) {
  42455. return true;
  42456. }
  42457. if (this._metallicTexture === texture) {
  42458. return true;
  42459. }
  42460. if (this._microSurfaceTexture === texture) {
  42461. return true;
  42462. }
  42463. if (this._bumpTexture === texture) {
  42464. return true;
  42465. }
  42466. if (this._lightmapTexture === texture) {
  42467. return true;
  42468. }
  42469. if (this._refractionTexture === texture) {
  42470. return true;
  42471. }
  42472. return false;
  42473. };
  42474. /**
  42475. * Makes a duplicate of the current material.
  42476. * @param name - name to use for the new material.
  42477. */
  42478. PBRMaterial.prototype.clone = function (name) {
  42479. var _this = this;
  42480. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42481. clone.id = name;
  42482. clone.name = name;
  42483. return clone;
  42484. };
  42485. /**
  42486. * Serializes this PBR Material.
  42487. * @returns - An object with the serialized material.
  42488. */
  42489. PBRMaterial.prototype.serialize = function () {
  42490. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42491. serializationObject.customType = "BABYLON.PBRMaterial";
  42492. return serializationObject;
  42493. };
  42494. // Statics
  42495. /**
  42496. * Parses a PBR Material from a serialized object.
  42497. * @param source - Serialized object.
  42498. * @param scene - BJS scene instance.
  42499. * @param rootUrl - url for the scene object
  42500. * @returns - PBRMaterial
  42501. */
  42502. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42503. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42504. };
  42505. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42506. /**
  42507. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42508. */
  42509. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42510. /**
  42511. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42512. */
  42513. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42514. /**
  42515. * 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.
  42516. * They are also discarded below the alpha cutoff threshold to improve performances.
  42517. */
  42518. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42519. __decorate([
  42520. BABYLON.serialize(),
  42521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42522. ], PBRMaterial.prototype, "directIntensity", void 0);
  42523. __decorate([
  42524. BABYLON.serialize(),
  42525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42526. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42527. __decorate([
  42528. BABYLON.serialize(),
  42529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42530. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42531. __decorate([
  42532. BABYLON.serialize(),
  42533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42534. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42535. __decorate([
  42536. BABYLON.serialize(),
  42537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42538. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42539. __decorate([
  42540. BABYLON.serializeAsTexture(),
  42541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42542. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42543. __decorate([
  42544. BABYLON.serializeAsTexture(),
  42545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42546. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42547. __decorate([
  42548. BABYLON.serialize(),
  42549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42550. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42551. __decorate([
  42552. BABYLON.serializeAsTexture(),
  42553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42554. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42555. __decorate([
  42556. BABYLON.serializeAsTexture(),
  42557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42558. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42559. __decorate([
  42560. BABYLON.serializeAsTexture(),
  42561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42562. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42563. __decorate([
  42564. BABYLON.serializeAsTexture(),
  42565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42566. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42567. __decorate([
  42568. BABYLON.serializeAsTexture(),
  42569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42570. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42571. __decorate([
  42572. BABYLON.serialize(),
  42573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42574. ], PBRMaterial.prototype, "metallic", void 0);
  42575. __decorate([
  42576. BABYLON.serialize(),
  42577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42578. ], PBRMaterial.prototype, "roughness", void 0);
  42579. __decorate([
  42580. BABYLON.serializeAsTexture(),
  42581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42582. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42583. __decorate([
  42584. BABYLON.serializeAsTexture(),
  42585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42586. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42587. __decorate([
  42588. BABYLON.serializeAsTexture(),
  42589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42590. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42591. __decorate([
  42592. BABYLON.serializeAsTexture(),
  42593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42594. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42595. __decorate([
  42596. BABYLON.serializeAsColor3("ambient"),
  42597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42598. ], PBRMaterial.prototype, "ambientColor", void 0);
  42599. __decorate([
  42600. BABYLON.serializeAsColor3("albedo"),
  42601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42602. ], PBRMaterial.prototype, "albedoColor", void 0);
  42603. __decorate([
  42604. BABYLON.serializeAsColor3("reflectivity"),
  42605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42606. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42607. __decorate([
  42608. BABYLON.serializeAsColor3("reflection"),
  42609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42610. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42611. __decorate([
  42612. BABYLON.serializeAsColor3("emissive"),
  42613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42614. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42615. __decorate([
  42616. BABYLON.serialize(),
  42617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42618. ], PBRMaterial.prototype, "microSurface", void 0);
  42619. __decorate([
  42620. BABYLON.serialize(),
  42621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42622. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42623. __decorate([
  42624. BABYLON.serialize(),
  42625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42626. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42627. __decorate([
  42628. BABYLON.serialize(),
  42629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42630. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42631. __decorate([
  42632. BABYLON.serialize(),
  42633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42634. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42635. __decorate([
  42636. BABYLON.serialize(),
  42637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42638. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42639. __decorate([
  42640. BABYLON.serialize(),
  42641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42642. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42643. __decorate([
  42644. BABYLON.serialize(),
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42646. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42647. __decorate([
  42648. BABYLON.serialize(),
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42650. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42651. __decorate([
  42652. BABYLON.serialize(),
  42653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42654. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42655. __decorate([
  42656. BABYLON.serialize(),
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42658. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42659. __decorate([
  42660. BABYLON.serialize(),
  42661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42662. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42663. __decorate([
  42664. BABYLON.serialize(),
  42665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42666. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42667. __decorate([
  42668. BABYLON.serialize(),
  42669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42670. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42671. __decorate([
  42672. BABYLON.serialize(),
  42673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42674. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42675. __decorate([
  42676. BABYLON.serialize(),
  42677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42678. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42679. __decorate([
  42680. BABYLON.serialize(),
  42681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42682. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42683. __decorate([
  42684. BABYLON.serialize(),
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42687. __decorate([
  42688. BABYLON.serialize(),
  42689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42690. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42691. __decorate([
  42692. BABYLON.serialize(),
  42693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42694. ], PBRMaterial.prototype, "useParallax", void 0);
  42695. __decorate([
  42696. BABYLON.serialize(),
  42697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42698. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42699. __decorate([
  42700. BABYLON.serialize(),
  42701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42702. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42703. __decorate([
  42704. BABYLON.serialize(),
  42705. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42706. ], PBRMaterial.prototype, "disableLighting", void 0);
  42707. __decorate([
  42708. BABYLON.serialize(),
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42710. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42711. __decorate([
  42712. BABYLON.serialize(),
  42713. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42714. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42715. __decorate([
  42716. BABYLON.serialize(),
  42717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42718. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42719. __decorate([
  42720. BABYLON.serialize(),
  42721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42722. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42723. __decorate([
  42724. BABYLON.serialize(),
  42725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42726. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42727. __decorate([
  42728. BABYLON.serialize(),
  42729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42730. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42731. __decorate([
  42732. BABYLON.serialize(),
  42733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42734. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42735. __decorate([
  42736. BABYLON.serializeAsTexture(),
  42737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42738. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42739. __decorate([
  42740. BABYLON.serialize(),
  42741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42742. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42743. __decorate([
  42744. BABYLON.serialize(),
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42746. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42747. __decorate([
  42748. BABYLON.serialize(),
  42749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42750. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42751. return PBRMaterial;
  42752. }(BABYLON.PBRBaseMaterial));
  42753. BABYLON.PBRMaterial = PBRMaterial;
  42754. })(BABYLON || (BABYLON = {}));
  42755. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42756. var BABYLON;
  42757. (function (BABYLON) {
  42758. /**
  42759. * The PBR material of BJS following the metal roughness convention.
  42760. *
  42761. * This fits to the PBR convention in the GLTF definition:
  42762. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42763. */
  42764. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42765. __extends(PBRMetallicRoughnessMaterial, _super);
  42766. /**
  42767. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42768. *
  42769. * @param name The material name
  42770. * @param scene The scene the material will be use in.
  42771. */
  42772. function PBRMetallicRoughnessMaterial(name, scene) {
  42773. var _this = _super.call(this, name, scene) || this;
  42774. _this._useRoughnessFromMetallicTextureAlpha = false;
  42775. _this._useRoughnessFromMetallicTextureGreen = true;
  42776. _this._useMetallnessFromMetallicTextureBlue = true;
  42777. _this.metallic = 1.0;
  42778. _this.roughness = 1.0;
  42779. return _this;
  42780. }
  42781. /**
  42782. * Return the currrent class name of the material.
  42783. */
  42784. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42785. return "PBRMetallicRoughnessMaterial";
  42786. };
  42787. /**
  42788. * Return the active textures of the material.
  42789. */
  42790. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42791. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42792. if (this.baseTexture) {
  42793. activeTextures.push(this.baseTexture);
  42794. }
  42795. if (this.metallicRoughnessTexture) {
  42796. activeTextures.push(this.metallicRoughnessTexture);
  42797. }
  42798. return activeTextures;
  42799. };
  42800. /**
  42801. * Checks to see if a texture is used in the material.
  42802. * @param texture - Base texture to use.
  42803. * @returns - Boolean specifying if a texture is used in the material.
  42804. */
  42805. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42806. if (_super.prototype.hasTexture.call(this, texture)) {
  42807. return true;
  42808. }
  42809. if (this.baseTexture === texture) {
  42810. return true;
  42811. }
  42812. if (this.metallicRoughnessTexture === texture) {
  42813. return true;
  42814. }
  42815. return false;
  42816. };
  42817. /**
  42818. * Makes a duplicate of the current material.
  42819. * @param name - name to use for the new material.
  42820. */
  42821. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42822. var _this = this;
  42823. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42824. clone.id = name;
  42825. clone.name = name;
  42826. return clone;
  42827. };
  42828. /**
  42829. * Serialize the material to a parsable JSON object.
  42830. */
  42831. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42832. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42833. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42834. return serializationObject;
  42835. };
  42836. /**
  42837. * Parses a JSON object correponding to the serialize function.
  42838. */
  42839. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42840. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42841. };
  42842. __decorate([
  42843. BABYLON.serializeAsColor3(),
  42844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42845. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42846. __decorate([
  42847. BABYLON.serializeAsTexture(),
  42848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42849. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42850. __decorate([
  42851. BABYLON.serialize(),
  42852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42853. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42854. __decorate([
  42855. BABYLON.serialize(),
  42856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42857. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42858. __decorate([
  42859. BABYLON.serializeAsTexture(),
  42860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42861. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42862. return PBRMetallicRoughnessMaterial;
  42863. }(BABYLON.PBRBaseSimpleMaterial));
  42864. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42865. })(BABYLON || (BABYLON = {}));
  42866. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42867. var BABYLON;
  42868. (function (BABYLON) {
  42869. /**
  42870. * The PBR material of BJS following the specular glossiness convention.
  42871. *
  42872. * This fits to the PBR convention in the GLTF definition:
  42873. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42874. */
  42875. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42876. __extends(PBRSpecularGlossinessMaterial, _super);
  42877. /**
  42878. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42879. *
  42880. * @param name The material name
  42881. * @param scene The scene the material will be use in.
  42882. */
  42883. function PBRSpecularGlossinessMaterial(name, scene) {
  42884. var _this = _super.call(this, name, scene) || this;
  42885. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42886. return _this;
  42887. }
  42888. /**
  42889. * Return the currrent class name of the material.
  42890. */
  42891. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42892. return "PBRSpecularGlossinessMaterial";
  42893. };
  42894. /**
  42895. * Return the active textures of the material.
  42896. */
  42897. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42898. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42899. if (this.diffuseTexture) {
  42900. activeTextures.push(this.diffuseTexture);
  42901. }
  42902. if (this.specularGlossinessTexture) {
  42903. activeTextures.push(this.specularGlossinessTexture);
  42904. }
  42905. return activeTextures;
  42906. };
  42907. /**
  42908. * Checks to see if a texture is used in the material.
  42909. * @param texture - Base texture to use.
  42910. * @returns - Boolean specifying if a texture is used in the material.
  42911. */
  42912. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42913. if (_super.prototype.hasTexture.call(this, texture)) {
  42914. return true;
  42915. }
  42916. if (this.diffuseTexture === texture) {
  42917. return true;
  42918. }
  42919. if (this.specularGlossinessTexture === texture) {
  42920. return true;
  42921. }
  42922. return false;
  42923. };
  42924. /**
  42925. * Makes a duplicate of the current material.
  42926. * @param name - name to use for the new material.
  42927. */
  42928. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42929. var _this = this;
  42930. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42931. clone.id = name;
  42932. clone.name = name;
  42933. return clone;
  42934. };
  42935. /**
  42936. * Serialize the material to a parsable JSON object.
  42937. */
  42938. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42939. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42940. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42941. return serializationObject;
  42942. };
  42943. /**
  42944. * Parses a JSON object correponding to the serialize function.
  42945. */
  42946. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42947. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42948. };
  42949. __decorate([
  42950. BABYLON.serializeAsColor3("diffuse"),
  42951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42952. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42953. __decorate([
  42954. BABYLON.serializeAsTexture(),
  42955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42956. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42957. __decorate([
  42958. BABYLON.serializeAsColor3("specular"),
  42959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42960. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42961. __decorate([
  42962. BABYLON.serialize(),
  42963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42964. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42965. __decorate([
  42966. BABYLON.serializeAsTexture(),
  42967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42968. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42969. return PBRSpecularGlossinessMaterial;
  42970. }(BABYLON.PBRBaseSimpleMaterial));
  42971. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42972. })(BABYLON || (BABYLON = {}));
  42973. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42974. var BABYLON;
  42975. (function (BABYLON) {
  42976. BABYLON.CameraInputTypes = {};
  42977. var CameraInputsManager = /** @class */ (function () {
  42978. function CameraInputsManager(camera) {
  42979. this.attached = {};
  42980. this.camera = camera;
  42981. this.checkInputs = function () { };
  42982. }
  42983. /**
  42984. * Add an input method to a camera.
  42985. * builtin inputs example: camera.inputs.addGamepad();
  42986. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42987. * @param input camera input method
  42988. */
  42989. CameraInputsManager.prototype.add = function (input) {
  42990. var type = input.getSimpleName();
  42991. if (this.attached[type]) {
  42992. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42993. return;
  42994. }
  42995. this.attached[type] = input;
  42996. input.camera = this.camera;
  42997. //for checkInputs, we are dynamically creating a function
  42998. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42999. if (input.checkInputs) {
  43000. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43001. }
  43002. if (this.attachedElement) {
  43003. input.attachControl(this.attachedElement);
  43004. }
  43005. };
  43006. /**
  43007. * Remove a specific input method from a camera
  43008. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43009. * @param inputToRemove camera input method
  43010. */
  43011. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43012. for (var cam in this.attached) {
  43013. var input = this.attached[cam];
  43014. if (input === inputToRemove) {
  43015. input.detachControl(this.attachedElement);
  43016. input.camera = null;
  43017. delete this.attached[cam];
  43018. this.rebuildInputCheck();
  43019. }
  43020. }
  43021. };
  43022. CameraInputsManager.prototype.removeByType = function (inputType) {
  43023. for (var cam in this.attached) {
  43024. var input = this.attached[cam];
  43025. if (input.getClassName() === inputType) {
  43026. input.detachControl(this.attachedElement);
  43027. input.camera = null;
  43028. delete this.attached[cam];
  43029. this.rebuildInputCheck();
  43030. }
  43031. }
  43032. };
  43033. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43034. var current = this.checkInputs;
  43035. return function () {
  43036. current();
  43037. fn();
  43038. };
  43039. };
  43040. CameraInputsManager.prototype.attachInput = function (input) {
  43041. if (this.attachedElement) {
  43042. input.attachControl(this.attachedElement, this.noPreventDefault);
  43043. }
  43044. };
  43045. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43046. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43047. if (this.attachedElement) {
  43048. return;
  43049. }
  43050. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43051. this.attachedElement = element;
  43052. this.noPreventDefault = noPreventDefault;
  43053. for (var cam in this.attached) {
  43054. this.attached[cam].attachControl(element, noPreventDefault);
  43055. }
  43056. };
  43057. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43058. if (disconnect === void 0) { disconnect = false; }
  43059. if (this.attachedElement !== element) {
  43060. return;
  43061. }
  43062. for (var cam in this.attached) {
  43063. this.attached[cam].detachControl(element);
  43064. if (disconnect) {
  43065. this.attached[cam].camera = null;
  43066. }
  43067. }
  43068. this.attachedElement = null;
  43069. };
  43070. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43071. this.checkInputs = function () { };
  43072. for (var cam in this.attached) {
  43073. var input = this.attached[cam];
  43074. if (input.checkInputs) {
  43075. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43076. }
  43077. }
  43078. };
  43079. /**
  43080. * Remove all attached input methods from a camera
  43081. */
  43082. CameraInputsManager.prototype.clear = function () {
  43083. if (this.attachedElement) {
  43084. this.detachElement(this.attachedElement, true);
  43085. }
  43086. this.attached = {};
  43087. this.attachedElement = null;
  43088. this.checkInputs = function () { };
  43089. };
  43090. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43091. var inputs = {};
  43092. for (var cam in this.attached) {
  43093. var input = this.attached[cam];
  43094. var res = BABYLON.SerializationHelper.Serialize(input);
  43095. inputs[input.getClassName()] = res;
  43096. }
  43097. serializedCamera.inputsmgr = inputs;
  43098. };
  43099. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43100. var parsedInputs = parsedCamera.inputsmgr;
  43101. if (parsedInputs) {
  43102. this.clear();
  43103. for (var n in parsedInputs) {
  43104. var construct = BABYLON.CameraInputTypes[n];
  43105. if (construct) {
  43106. var parsedinput = parsedInputs[n];
  43107. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43108. this.add(input);
  43109. }
  43110. }
  43111. }
  43112. else {
  43113. //2016-03-08 this part is for managing backward compatibility
  43114. for (var n in this.attached) {
  43115. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43116. if (construct) {
  43117. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43118. this.remove(this.attached[n]);
  43119. this.add(input);
  43120. }
  43121. }
  43122. }
  43123. };
  43124. return CameraInputsManager;
  43125. }());
  43126. BABYLON.CameraInputsManager = CameraInputsManager;
  43127. })(BABYLON || (BABYLON = {}));
  43128. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43129. var BABYLON;
  43130. (function (BABYLON) {
  43131. var TargetCamera = /** @class */ (function (_super) {
  43132. __extends(TargetCamera, _super);
  43133. function TargetCamera(name, position, scene) {
  43134. var _this = _super.call(this, name, position, scene) || this;
  43135. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43136. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43137. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43138. _this.speed = 2.0;
  43139. _this.noRotationConstraint = false;
  43140. _this.lockedTarget = null;
  43141. _this._currentTarget = BABYLON.Vector3.Zero();
  43142. _this._viewMatrix = BABYLON.Matrix.Zero();
  43143. _this._camMatrix = BABYLON.Matrix.Zero();
  43144. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43145. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43146. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43147. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43148. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43149. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43150. _this._tempMatrix = BABYLON.Matrix.Zero();
  43151. return _this;
  43152. }
  43153. TargetCamera.prototype.getFrontPosition = function (distance) {
  43154. this.getWorldMatrix();
  43155. var direction = this.getTarget().subtract(this.position);
  43156. direction.normalize();
  43157. direction.scaleInPlace(distance);
  43158. return this.globalPosition.add(direction);
  43159. };
  43160. TargetCamera.prototype._getLockedTargetPosition = function () {
  43161. if (!this.lockedTarget) {
  43162. return null;
  43163. }
  43164. if (this.lockedTarget.absolutePosition) {
  43165. this.lockedTarget.computeWorldMatrix();
  43166. }
  43167. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43168. };
  43169. TargetCamera.prototype.storeState = function () {
  43170. this._storedPosition = this.position.clone();
  43171. this._storedRotation = this.rotation.clone();
  43172. if (this.rotationQuaternion) {
  43173. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43174. }
  43175. return _super.prototype.storeState.call(this);
  43176. };
  43177. /**
  43178. * Restored camera state. You must call storeState() first
  43179. */
  43180. TargetCamera.prototype._restoreStateValues = function () {
  43181. if (!_super.prototype._restoreStateValues.call(this)) {
  43182. return false;
  43183. }
  43184. this.position = this._storedPosition.clone();
  43185. this.rotation = this._storedRotation.clone();
  43186. if (this.rotationQuaternion) {
  43187. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43188. }
  43189. this.cameraDirection.copyFromFloats(0, 0, 0);
  43190. this.cameraRotation.copyFromFloats(0, 0);
  43191. return true;
  43192. };
  43193. // Cache
  43194. TargetCamera.prototype._initCache = function () {
  43195. _super.prototype._initCache.call(this);
  43196. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43197. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43198. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43199. };
  43200. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43201. if (!ignoreParentClass) {
  43202. _super.prototype._updateCache.call(this);
  43203. }
  43204. var lockedTargetPosition = this._getLockedTargetPosition();
  43205. if (!lockedTargetPosition) {
  43206. this._cache.lockedTarget = null;
  43207. }
  43208. else {
  43209. if (!this._cache.lockedTarget) {
  43210. this._cache.lockedTarget = lockedTargetPosition.clone();
  43211. }
  43212. else {
  43213. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43214. }
  43215. }
  43216. this._cache.rotation.copyFrom(this.rotation);
  43217. if (this.rotationQuaternion)
  43218. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43219. };
  43220. // Synchronized
  43221. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43222. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43223. return false;
  43224. }
  43225. var lockedTargetPosition = this._getLockedTargetPosition();
  43226. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43227. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43228. };
  43229. // Methods
  43230. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43231. var engine = this.getEngine();
  43232. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43233. };
  43234. // Target
  43235. TargetCamera.prototype.setTarget = function (target) {
  43236. this.upVector.normalize();
  43237. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43238. this._camMatrix.invert();
  43239. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43240. var vDir = target.subtract(this.position);
  43241. if (vDir.x >= 0.0) {
  43242. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43243. }
  43244. else {
  43245. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43246. }
  43247. this.rotation.z = 0;
  43248. if (isNaN(this.rotation.x)) {
  43249. this.rotation.x = 0;
  43250. }
  43251. if (isNaN(this.rotation.y)) {
  43252. this.rotation.y = 0;
  43253. }
  43254. if (isNaN(this.rotation.z)) {
  43255. this.rotation.z = 0;
  43256. }
  43257. if (this.rotationQuaternion) {
  43258. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43259. }
  43260. };
  43261. /**
  43262. * Return the current target position of the camera. This value is expressed in local space.
  43263. */
  43264. TargetCamera.prototype.getTarget = function () {
  43265. return this._currentTarget;
  43266. };
  43267. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43268. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43269. };
  43270. TargetCamera.prototype._updatePosition = function () {
  43271. if (this.parent) {
  43272. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43273. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43274. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43275. return;
  43276. }
  43277. this.position.addInPlace(this.cameraDirection);
  43278. };
  43279. TargetCamera.prototype._checkInputs = function () {
  43280. var needToMove = this._decideIfNeedsToMove();
  43281. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43282. // Move
  43283. if (needToMove) {
  43284. this._updatePosition();
  43285. }
  43286. // Rotate
  43287. if (needToRotate) {
  43288. this.rotation.x += this.cameraRotation.x;
  43289. this.rotation.y += this.cameraRotation.y;
  43290. //rotate, if quaternion is set and rotation was used
  43291. if (this.rotationQuaternion) {
  43292. var len = this.rotation.lengthSquared();
  43293. if (len) {
  43294. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43295. }
  43296. }
  43297. if (!this.noRotationConstraint) {
  43298. var limit = (Math.PI / 2) * 0.95;
  43299. if (this.rotation.x > limit)
  43300. this.rotation.x = limit;
  43301. if (this.rotation.x < -limit)
  43302. this.rotation.x = -limit;
  43303. }
  43304. }
  43305. // Inertia
  43306. if (needToMove) {
  43307. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43308. this.cameraDirection.x = 0;
  43309. }
  43310. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43311. this.cameraDirection.y = 0;
  43312. }
  43313. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43314. this.cameraDirection.z = 0;
  43315. }
  43316. this.cameraDirection.scaleInPlace(this.inertia);
  43317. }
  43318. if (needToRotate) {
  43319. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43320. this.cameraRotation.x = 0;
  43321. }
  43322. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43323. this.cameraRotation.y = 0;
  43324. }
  43325. this.cameraRotation.scaleInPlace(this.inertia);
  43326. }
  43327. _super.prototype._checkInputs.call(this);
  43328. };
  43329. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43330. if (this.rotationQuaternion) {
  43331. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43332. }
  43333. else {
  43334. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43335. }
  43336. //update the up vector!
  43337. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43338. };
  43339. TargetCamera.prototype._getViewMatrix = function () {
  43340. if (this.lockedTarget) {
  43341. this.setTarget(this._getLockedTargetPosition());
  43342. }
  43343. // Compute
  43344. this._updateCameraRotationMatrix();
  43345. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43346. // Computing target and final matrix
  43347. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43348. if (this.getScene().useRightHandedSystem) {
  43349. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43350. }
  43351. else {
  43352. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43353. }
  43354. return this._viewMatrix;
  43355. };
  43356. /**
  43357. * @override
  43358. * Override Camera.createRigCamera
  43359. */
  43360. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43361. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43362. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43363. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43364. if (!this.rotationQuaternion) {
  43365. this.rotationQuaternion = new BABYLON.Quaternion();
  43366. }
  43367. rigCamera._cameraRigParams = {};
  43368. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43369. }
  43370. return rigCamera;
  43371. }
  43372. return null;
  43373. };
  43374. /**
  43375. * @override
  43376. * Override Camera._updateRigCameras
  43377. */
  43378. TargetCamera.prototype._updateRigCameras = function () {
  43379. var camLeft = this._rigCameras[0];
  43380. var camRight = this._rigCameras[1];
  43381. switch (this.cameraRigMode) {
  43382. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43383. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43384. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43385. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43386. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43387. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43388. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43389. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43390. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43391. camLeft.setTarget(this.getTarget());
  43392. camRight.setTarget(this.getTarget());
  43393. break;
  43394. case BABYLON.Camera.RIG_MODE_VR:
  43395. if (camLeft.rotationQuaternion) {
  43396. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43397. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43398. }
  43399. else {
  43400. camLeft.rotation.copyFrom(this.rotation);
  43401. camRight.rotation.copyFrom(this.rotation);
  43402. }
  43403. camLeft.position.copyFrom(this.position);
  43404. camRight.position.copyFrom(this.position);
  43405. break;
  43406. }
  43407. _super.prototype._updateRigCameras.call(this);
  43408. };
  43409. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43410. if (!this._rigCamTransformMatrix) {
  43411. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43412. }
  43413. var target = this.getTarget();
  43414. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43415. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43416. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43417. };
  43418. TargetCamera.prototype.getClassName = function () {
  43419. return "TargetCamera";
  43420. };
  43421. __decorate([
  43422. BABYLON.serializeAsVector3()
  43423. ], TargetCamera.prototype, "rotation", void 0);
  43424. __decorate([
  43425. BABYLON.serialize()
  43426. ], TargetCamera.prototype, "speed", void 0);
  43427. __decorate([
  43428. BABYLON.serializeAsMeshReference("lockedTargetId")
  43429. ], TargetCamera.prototype, "lockedTarget", void 0);
  43430. return TargetCamera;
  43431. }(BABYLON.Camera));
  43432. BABYLON.TargetCamera = TargetCamera;
  43433. })(BABYLON || (BABYLON = {}));
  43434. //# sourceMappingURL=babylon.targetCamera.js.map
  43435. var BABYLON;
  43436. (function (BABYLON) {
  43437. var FreeCameraMouseInput = /** @class */ (function () {
  43438. function FreeCameraMouseInput(touchEnabled) {
  43439. if (touchEnabled === void 0) { touchEnabled = true; }
  43440. this.touchEnabled = touchEnabled;
  43441. this.buttons = [0, 1, 2];
  43442. this.angularSensibility = 2000.0;
  43443. this.previousPosition = null;
  43444. }
  43445. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43446. var _this = this;
  43447. var engine = this.camera.getEngine();
  43448. if (!this._pointerInput) {
  43449. this._pointerInput = function (p, s) {
  43450. var evt = p.event;
  43451. if (engine.isInVRExclusivePointerMode) {
  43452. return;
  43453. }
  43454. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43455. return;
  43456. }
  43457. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43458. return;
  43459. }
  43460. var srcElement = (evt.srcElement || evt.target);
  43461. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43462. try {
  43463. srcElement.setPointerCapture(evt.pointerId);
  43464. }
  43465. catch (e) {
  43466. //Nothing to do with the error. Execution will continue.
  43467. }
  43468. _this.previousPosition = {
  43469. x: evt.clientX,
  43470. y: evt.clientY
  43471. };
  43472. if (!noPreventDefault) {
  43473. evt.preventDefault();
  43474. element.focus();
  43475. }
  43476. }
  43477. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43478. try {
  43479. srcElement.releasePointerCapture(evt.pointerId);
  43480. }
  43481. catch (e) {
  43482. //Nothing to do with the error.
  43483. }
  43484. _this.previousPosition = null;
  43485. if (!noPreventDefault) {
  43486. evt.preventDefault();
  43487. }
  43488. }
  43489. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43490. if (!_this.previousPosition || engine.isPointerLock) {
  43491. return;
  43492. }
  43493. var offsetX = evt.clientX - _this.previousPosition.x;
  43494. var offsetY = evt.clientY - _this.previousPosition.y;
  43495. if (_this.camera.getScene().useRightHandedSystem) {
  43496. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43497. }
  43498. else {
  43499. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43500. }
  43501. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43502. _this.previousPosition = {
  43503. x: evt.clientX,
  43504. y: evt.clientY
  43505. };
  43506. if (!noPreventDefault) {
  43507. evt.preventDefault();
  43508. }
  43509. }
  43510. };
  43511. }
  43512. this._onMouseMove = function (evt) {
  43513. if (!engine.isPointerLock) {
  43514. return;
  43515. }
  43516. if (engine.isInVRExclusivePointerMode) {
  43517. return;
  43518. }
  43519. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43520. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43521. if (_this.camera.getScene().useRightHandedSystem) {
  43522. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43523. }
  43524. else {
  43525. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43526. }
  43527. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43528. _this.previousPosition = null;
  43529. if (!noPreventDefault) {
  43530. evt.preventDefault();
  43531. }
  43532. };
  43533. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43534. element.addEventListener("mousemove", this._onMouseMove, false);
  43535. };
  43536. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43537. if (this._observer && element) {
  43538. this.camera.getScene().onPointerObservable.remove(this._observer);
  43539. if (this._onMouseMove) {
  43540. element.removeEventListener("mousemove", this._onMouseMove);
  43541. }
  43542. this._observer = null;
  43543. this._onMouseMove = null;
  43544. this.previousPosition = null;
  43545. }
  43546. };
  43547. FreeCameraMouseInput.prototype.getClassName = function () {
  43548. return "FreeCameraMouseInput";
  43549. };
  43550. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43551. return "mouse";
  43552. };
  43553. __decorate([
  43554. BABYLON.serialize()
  43555. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43556. __decorate([
  43557. BABYLON.serialize()
  43558. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43559. return FreeCameraMouseInput;
  43560. }());
  43561. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43562. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43563. })(BABYLON || (BABYLON = {}));
  43564. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43565. var BABYLON;
  43566. (function (BABYLON) {
  43567. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43568. function FreeCameraKeyboardMoveInput() {
  43569. this._keys = new Array();
  43570. this.keysUp = [38];
  43571. this.keysDown = [40];
  43572. this.keysLeft = [37];
  43573. this.keysRight = [39];
  43574. }
  43575. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43576. var _this = this;
  43577. if (this._onCanvasBlurObserver) {
  43578. return;
  43579. }
  43580. this._scene = this.camera.getScene();
  43581. this._engine = this._scene.getEngine();
  43582. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43583. _this._keys = [];
  43584. });
  43585. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43586. var evt = info.event;
  43587. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43588. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43589. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43590. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43591. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43592. var index = _this._keys.indexOf(evt.keyCode);
  43593. if (index === -1) {
  43594. _this._keys.push(evt.keyCode);
  43595. }
  43596. if (!noPreventDefault) {
  43597. evt.preventDefault();
  43598. }
  43599. }
  43600. }
  43601. else {
  43602. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43603. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43604. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43605. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43606. var index = _this._keys.indexOf(evt.keyCode);
  43607. if (index >= 0) {
  43608. _this._keys.splice(index, 1);
  43609. }
  43610. if (!noPreventDefault) {
  43611. evt.preventDefault();
  43612. }
  43613. }
  43614. }
  43615. });
  43616. };
  43617. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43618. if (this._scene) {
  43619. if (this._onKeyboardObserver) {
  43620. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43621. }
  43622. if (this._onCanvasBlurObserver) {
  43623. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43624. }
  43625. this._onKeyboardObserver = null;
  43626. this._onCanvasBlurObserver = null;
  43627. }
  43628. this._keys = [];
  43629. };
  43630. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43631. if (this._onKeyboardObserver) {
  43632. var camera = this.camera;
  43633. // Keyboard
  43634. for (var index = 0; index < this._keys.length; index++) {
  43635. var keyCode = this._keys[index];
  43636. var speed = camera._computeLocalCameraSpeed();
  43637. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43638. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43639. }
  43640. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43641. camera._localDirection.copyFromFloats(0, 0, speed);
  43642. }
  43643. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43644. camera._localDirection.copyFromFloats(speed, 0, 0);
  43645. }
  43646. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43647. camera._localDirection.copyFromFloats(0, 0, -speed);
  43648. }
  43649. if (camera.getScene().useRightHandedSystem) {
  43650. camera._localDirection.z *= -1;
  43651. }
  43652. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43653. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43654. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43655. }
  43656. }
  43657. };
  43658. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43659. return "FreeCameraKeyboardMoveInput";
  43660. };
  43661. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43662. this._keys = [];
  43663. };
  43664. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43665. return "keyboard";
  43666. };
  43667. __decorate([
  43668. BABYLON.serialize()
  43669. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43670. __decorate([
  43671. BABYLON.serialize()
  43672. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43673. __decorate([
  43674. BABYLON.serialize()
  43675. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43676. __decorate([
  43677. BABYLON.serialize()
  43678. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43679. return FreeCameraKeyboardMoveInput;
  43680. }());
  43681. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43682. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43683. })(BABYLON || (BABYLON = {}));
  43684. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43685. var BABYLON;
  43686. (function (BABYLON) {
  43687. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43688. __extends(FreeCameraInputsManager, _super);
  43689. function FreeCameraInputsManager(camera) {
  43690. return _super.call(this, camera) || this;
  43691. }
  43692. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43693. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43694. return this;
  43695. };
  43696. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43697. if (touchEnabled === void 0) { touchEnabled = true; }
  43698. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43699. return this;
  43700. };
  43701. FreeCameraInputsManager.prototype.addGamepad = function () {
  43702. this.add(new BABYLON.FreeCameraGamepadInput());
  43703. return this;
  43704. };
  43705. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43706. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43707. return this;
  43708. };
  43709. FreeCameraInputsManager.prototype.addTouch = function () {
  43710. this.add(new BABYLON.FreeCameraTouchInput());
  43711. return this;
  43712. };
  43713. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43714. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43715. return this;
  43716. };
  43717. return FreeCameraInputsManager;
  43718. }(BABYLON.CameraInputsManager));
  43719. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43720. })(BABYLON || (BABYLON = {}));
  43721. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43722. var BABYLON;
  43723. (function (BABYLON) {
  43724. var FreeCamera = /** @class */ (function (_super) {
  43725. __extends(FreeCamera, _super);
  43726. function FreeCamera(name, position, scene) {
  43727. var _this = _super.call(this, name, position, scene) || this;
  43728. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43729. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43730. _this.checkCollisions = false;
  43731. _this.applyGravity = false;
  43732. _this._needMoveForGravity = false;
  43733. _this._oldPosition = BABYLON.Vector3.Zero();
  43734. _this._diffPosition = BABYLON.Vector3.Zero();
  43735. _this._newPosition = BABYLON.Vector3.Zero();
  43736. // Collisions
  43737. _this._collisionMask = -1;
  43738. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43739. if (collidedMesh === void 0) { collidedMesh = null; }
  43740. //TODO move this to the collision coordinator!
  43741. if (_this.getScene().workerCollisions)
  43742. newPosition.multiplyInPlace(_this._collider._radius);
  43743. var updatePosition = function (newPos) {
  43744. _this._newPosition.copyFrom(newPos);
  43745. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43746. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43747. _this.position.addInPlace(_this._diffPosition);
  43748. if (_this.onCollide && collidedMesh) {
  43749. _this.onCollide(collidedMesh);
  43750. }
  43751. }
  43752. };
  43753. updatePosition(newPosition);
  43754. };
  43755. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43756. _this.inputs.addKeyboard().addMouse();
  43757. return _this;
  43758. }
  43759. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43760. //-- begin properties for backward compatibility for inputs
  43761. /**
  43762. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43763. * Higher values reduce sensitivity.
  43764. */
  43765. get: function () {
  43766. var mouse = this.inputs.attached["mouse"];
  43767. if (mouse)
  43768. return mouse.angularSensibility;
  43769. return 0;
  43770. },
  43771. /**
  43772. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43773. * Higher values reduce sensitivity.
  43774. */
  43775. set: function (value) {
  43776. var mouse = this.inputs.attached["mouse"];
  43777. if (mouse)
  43778. mouse.angularSensibility = value;
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43784. get: function () {
  43785. var keyboard = this.inputs.attached["keyboard"];
  43786. if (keyboard)
  43787. return keyboard.keysUp;
  43788. return [];
  43789. },
  43790. set: function (value) {
  43791. var keyboard = this.inputs.attached["keyboard"];
  43792. if (keyboard)
  43793. keyboard.keysUp = value;
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43799. get: function () {
  43800. var keyboard = this.inputs.attached["keyboard"];
  43801. if (keyboard)
  43802. return keyboard.keysDown;
  43803. return [];
  43804. },
  43805. set: function (value) {
  43806. var keyboard = this.inputs.attached["keyboard"];
  43807. if (keyboard)
  43808. keyboard.keysDown = value;
  43809. },
  43810. enumerable: true,
  43811. configurable: true
  43812. });
  43813. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43814. get: function () {
  43815. var keyboard = this.inputs.attached["keyboard"];
  43816. if (keyboard)
  43817. return keyboard.keysLeft;
  43818. return [];
  43819. },
  43820. set: function (value) {
  43821. var keyboard = this.inputs.attached["keyboard"];
  43822. if (keyboard)
  43823. keyboard.keysLeft = value;
  43824. },
  43825. enumerable: true,
  43826. configurable: true
  43827. });
  43828. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43829. get: function () {
  43830. var keyboard = this.inputs.attached["keyboard"];
  43831. if (keyboard)
  43832. return keyboard.keysRight;
  43833. return [];
  43834. },
  43835. set: function (value) {
  43836. var keyboard = this.inputs.attached["keyboard"];
  43837. if (keyboard)
  43838. keyboard.keysRight = value;
  43839. },
  43840. enumerable: true,
  43841. configurable: true
  43842. });
  43843. // Controls
  43844. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43845. this.inputs.attachElement(element, noPreventDefault);
  43846. };
  43847. FreeCamera.prototype.detachControl = function (element) {
  43848. this.inputs.detachElement(element);
  43849. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43850. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43851. };
  43852. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43853. get: function () {
  43854. return this._collisionMask;
  43855. },
  43856. set: function (mask) {
  43857. this._collisionMask = !isNaN(mask) ? mask : -1;
  43858. },
  43859. enumerable: true,
  43860. configurable: true
  43861. });
  43862. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43863. var globalPosition;
  43864. if (this.parent) {
  43865. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43866. }
  43867. else {
  43868. globalPosition = this.position;
  43869. }
  43870. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43871. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43872. if (!this._collider) {
  43873. this._collider = new BABYLON.Collider();
  43874. }
  43875. this._collider._radius = this.ellipsoid;
  43876. this._collider.collisionMask = this._collisionMask;
  43877. //no need for clone, as long as gravity is not on.
  43878. var actualDisplacement = displacement;
  43879. //add gravity to the direction to prevent the dual-collision checking
  43880. if (this.applyGravity) {
  43881. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43882. actualDisplacement = displacement.add(this.getScene().gravity);
  43883. }
  43884. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43885. };
  43886. FreeCamera.prototype._checkInputs = function () {
  43887. if (!this._localDirection) {
  43888. this._localDirection = BABYLON.Vector3.Zero();
  43889. this._transformedDirection = BABYLON.Vector3.Zero();
  43890. }
  43891. this.inputs.checkInputs();
  43892. _super.prototype._checkInputs.call(this);
  43893. };
  43894. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43895. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43896. };
  43897. FreeCamera.prototype._updatePosition = function () {
  43898. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43899. this._collideWithWorld(this.cameraDirection);
  43900. }
  43901. else {
  43902. _super.prototype._updatePosition.call(this);
  43903. }
  43904. };
  43905. FreeCamera.prototype.dispose = function () {
  43906. this.inputs.clear();
  43907. _super.prototype.dispose.call(this);
  43908. };
  43909. FreeCamera.prototype.getClassName = function () {
  43910. return "FreeCamera";
  43911. };
  43912. __decorate([
  43913. BABYLON.serializeAsVector3()
  43914. ], FreeCamera.prototype, "ellipsoid", void 0);
  43915. __decorate([
  43916. BABYLON.serializeAsVector3()
  43917. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43918. __decorate([
  43919. BABYLON.serialize()
  43920. ], FreeCamera.prototype, "checkCollisions", void 0);
  43921. __decorate([
  43922. BABYLON.serialize()
  43923. ], FreeCamera.prototype, "applyGravity", void 0);
  43924. return FreeCamera;
  43925. }(BABYLON.TargetCamera));
  43926. BABYLON.FreeCamera = FreeCamera;
  43927. })(BABYLON || (BABYLON = {}));
  43928. //# sourceMappingURL=babylon.freeCamera.js.map
  43929. var BABYLON;
  43930. (function (BABYLON) {
  43931. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43932. function ArcRotateCameraKeyboardMoveInput() {
  43933. this._keys = new Array();
  43934. this.keysUp = [38];
  43935. this.keysDown = [40];
  43936. this.keysLeft = [37];
  43937. this.keysRight = [39];
  43938. this.keysReset = [220];
  43939. this.panningSensibility = 50.0;
  43940. this.zoomingSensibility = 25.0;
  43941. this.useAltToZoom = true;
  43942. }
  43943. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43944. var _this = this;
  43945. if (this._onCanvasBlurObserver) {
  43946. return;
  43947. }
  43948. this._scene = this.camera.getScene();
  43949. this._engine = this._scene.getEngine();
  43950. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43951. _this._keys = [];
  43952. });
  43953. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43954. var evt = info.event;
  43955. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43956. _this._ctrlPressed = evt.ctrlKey;
  43957. _this._altPressed = evt.altKey;
  43958. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43959. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43960. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43961. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43962. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43963. var index = _this._keys.indexOf(evt.keyCode);
  43964. if (index === -1) {
  43965. _this._keys.push(evt.keyCode);
  43966. }
  43967. if (evt.preventDefault) {
  43968. if (!noPreventDefault) {
  43969. evt.preventDefault();
  43970. }
  43971. }
  43972. }
  43973. }
  43974. else {
  43975. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43976. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43977. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43978. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43979. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43980. var index = _this._keys.indexOf(evt.keyCode);
  43981. if (index >= 0) {
  43982. _this._keys.splice(index, 1);
  43983. }
  43984. if (evt.preventDefault) {
  43985. if (!noPreventDefault) {
  43986. evt.preventDefault();
  43987. }
  43988. }
  43989. }
  43990. }
  43991. });
  43992. };
  43993. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43994. if (this._scene) {
  43995. if (this._onKeyboardObserver) {
  43996. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43997. }
  43998. if (this._onCanvasBlurObserver) {
  43999. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44000. }
  44001. this._onKeyboardObserver = null;
  44002. this._onCanvasBlurObserver = null;
  44003. }
  44004. this._keys = [];
  44005. };
  44006. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44007. if (this._onKeyboardObserver) {
  44008. var camera = this.camera;
  44009. for (var index = 0; index < this._keys.length; index++) {
  44010. var keyCode = this._keys[index];
  44011. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44012. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44013. camera.inertialPanningX -= 1 / this.panningSensibility;
  44014. }
  44015. else {
  44016. camera.inertialAlphaOffset -= 0.01;
  44017. }
  44018. }
  44019. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44020. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44021. camera.inertialPanningY += 1 / this.panningSensibility;
  44022. }
  44023. else if (this._altPressed && this.useAltToZoom) {
  44024. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44025. }
  44026. else {
  44027. camera.inertialBetaOffset -= 0.01;
  44028. }
  44029. }
  44030. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44031. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44032. camera.inertialPanningX += 1 / this.panningSensibility;
  44033. }
  44034. else {
  44035. camera.inertialAlphaOffset += 0.01;
  44036. }
  44037. }
  44038. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44039. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44040. camera.inertialPanningY -= 1 / this.panningSensibility;
  44041. }
  44042. else if (this._altPressed && this.useAltToZoom) {
  44043. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44044. }
  44045. else {
  44046. camera.inertialBetaOffset += 0.01;
  44047. }
  44048. }
  44049. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44050. camera.restoreState();
  44051. }
  44052. }
  44053. }
  44054. };
  44055. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44056. return "ArcRotateCameraKeyboardMoveInput";
  44057. };
  44058. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44059. return "keyboard";
  44060. };
  44061. __decorate([
  44062. BABYLON.serialize()
  44063. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44064. __decorate([
  44065. BABYLON.serialize()
  44066. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44067. __decorate([
  44068. BABYLON.serialize()
  44069. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44070. __decorate([
  44071. BABYLON.serialize()
  44072. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44073. __decorate([
  44074. BABYLON.serialize()
  44075. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44076. __decorate([
  44077. BABYLON.serialize()
  44078. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44079. __decorate([
  44080. BABYLON.serialize()
  44081. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44082. __decorate([
  44083. BABYLON.serialize()
  44084. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44085. return ArcRotateCameraKeyboardMoveInput;
  44086. }());
  44087. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44088. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44089. })(BABYLON || (BABYLON = {}));
  44090. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44091. var BABYLON;
  44092. (function (BABYLON) {
  44093. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44094. function ArcRotateCameraMouseWheelInput() {
  44095. this.wheelPrecision = 3.0;
  44096. /**
  44097. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44098. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44099. */
  44100. this.wheelDeltaPercentage = 0;
  44101. }
  44102. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44103. var _this = this;
  44104. this._wheel = function (p, s) {
  44105. //sanity check - this should be a PointerWheel event.
  44106. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44107. return;
  44108. var event = p.event;
  44109. var delta = 0;
  44110. if (event.wheelDelta) {
  44111. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44112. }
  44113. else if (event.detail) {
  44114. delta = -event.detail / _this.wheelPrecision;
  44115. }
  44116. if (delta)
  44117. _this.camera.inertialRadiusOffset += delta;
  44118. if (event.preventDefault) {
  44119. if (!noPreventDefault) {
  44120. event.preventDefault();
  44121. }
  44122. }
  44123. };
  44124. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44125. };
  44126. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44127. if (this._observer && element) {
  44128. this.camera.getScene().onPointerObservable.remove(this._observer);
  44129. this._observer = null;
  44130. this._wheel = null;
  44131. }
  44132. };
  44133. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44134. return "ArcRotateCameraMouseWheelInput";
  44135. };
  44136. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44137. return "mousewheel";
  44138. };
  44139. __decorate([
  44140. BABYLON.serialize()
  44141. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44142. __decorate([
  44143. BABYLON.serialize()
  44144. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44145. return ArcRotateCameraMouseWheelInput;
  44146. }());
  44147. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44148. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44149. })(BABYLON || (BABYLON = {}));
  44150. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44151. var BABYLON;
  44152. (function (BABYLON) {
  44153. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44154. function ArcRotateCameraPointersInput() {
  44155. this.buttons = [0, 1, 2];
  44156. this.angularSensibilityX = 1000.0;
  44157. this.angularSensibilityY = 1000.0;
  44158. this.pinchPrecision = 12.0;
  44159. /**
  44160. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44161. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44162. */
  44163. this.pinchDeltaPercentage = 0;
  44164. this.panningSensibility = 1000.0;
  44165. this.multiTouchPanning = true;
  44166. this.multiTouchPanAndZoom = true;
  44167. this._isPanClick = false;
  44168. this.pinchInwards = true;
  44169. }
  44170. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44171. var _this = this;
  44172. var engine = this.camera.getEngine();
  44173. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44174. var pointA = null;
  44175. var pointB = null;
  44176. var previousPinchSquaredDistance = 0;
  44177. var initialDistance = 0;
  44178. var twoFingerActivityCount = 0;
  44179. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44180. this._pointerInput = function (p, s) {
  44181. var evt = p.event;
  44182. var isTouch = p.event.pointerType === "touch";
  44183. if (engine.isInVRExclusivePointerMode) {
  44184. return;
  44185. }
  44186. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44187. return;
  44188. }
  44189. var srcElement = (evt.srcElement || evt.target);
  44190. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44191. try {
  44192. srcElement.setPointerCapture(evt.pointerId);
  44193. }
  44194. catch (e) {
  44195. //Nothing to do with the error. Execution will continue.
  44196. }
  44197. // Manage panning with pan button click
  44198. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44199. // manage pointers
  44200. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44201. if (pointA === null) {
  44202. pointA = cacheSoloPointer;
  44203. }
  44204. else if (pointB === null) {
  44205. pointB = cacheSoloPointer;
  44206. }
  44207. if (!noPreventDefault) {
  44208. evt.preventDefault();
  44209. element.focus();
  44210. }
  44211. }
  44212. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44213. _this.camera.restoreState();
  44214. }
  44215. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44216. try {
  44217. srcElement.releasePointerCapture(evt.pointerId);
  44218. }
  44219. catch (e) {
  44220. //Nothing to do with the error.
  44221. }
  44222. cacheSoloPointer = null;
  44223. previousPinchSquaredDistance = 0;
  44224. previousMultiTouchPanPosition.isPaning = false;
  44225. previousMultiTouchPanPosition.isPinching = false;
  44226. twoFingerActivityCount = 0;
  44227. initialDistance = 0;
  44228. if (!isTouch) {
  44229. pointB = null; // Mouse and pen are mono pointer
  44230. }
  44231. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44232. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44233. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44234. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44235. if (engine.badOS) {
  44236. pointA = pointB = null;
  44237. }
  44238. else {
  44239. //only remove the impacted pointer in case of multitouch allowing on most
  44240. //platforms switching from rotate to zoom and pan seamlessly.
  44241. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44242. pointA = pointB;
  44243. pointB = null;
  44244. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44245. }
  44246. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44247. pointB = null;
  44248. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44249. }
  44250. else {
  44251. pointA = pointB = null;
  44252. }
  44253. }
  44254. if (!noPreventDefault) {
  44255. evt.preventDefault();
  44256. }
  44257. }
  44258. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44259. if (!noPreventDefault) {
  44260. evt.preventDefault();
  44261. }
  44262. // One button down
  44263. if (pointA && pointB === null && cacheSoloPointer) {
  44264. if (_this.panningSensibility !== 0 &&
  44265. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44266. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44267. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44268. }
  44269. else {
  44270. var offsetX = evt.clientX - cacheSoloPointer.x;
  44271. var offsetY = evt.clientY - cacheSoloPointer.y;
  44272. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44273. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44274. }
  44275. cacheSoloPointer.x = evt.clientX;
  44276. cacheSoloPointer.y = evt.clientY;
  44277. }
  44278. else if (pointA && pointB) {
  44279. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44280. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44281. ed.x = evt.clientX;
  44282. ed.y = evt.clientY;
  44283. var direction = _this.pinchInwards ? 1 : -1;
  44284. var distX = pointA.x - pointB.x;
  44285. var distY = pointA.y - pointB.y;
  44286. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44287. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44288. if (previousPinchSquaredDistance === 0) {
  44289. initialDistance = pinchDistance;
  44290. previousPinchSquaredDistance = pinchSquaredDistance;
  44291. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44292. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44293. return;
  44294. }
  44295. if (_this.multiTouchPanAndZoom) {
  44296. if (_this.pinchDeltaPercentage) {
  44297. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44298. }
  44299. else {
  44300. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44301. (_this.pinchPrecision *
  44302. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44303. direction);
  44304. }
  44305. if (_this.panningSensibility !== 0) {
  44306. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44307. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44308. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44309. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44310. previousMultiTouchPanPosition.x = pointersCenterX;
  44311. previousMultiTouchPanPosition.y = pointersCenterY;
  44312. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44313. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44314. }
  44315. }
  44316. else {
  44317. twoFingerActivityCount++;
  44318. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44319. if (_this.pinchDeltaPercentage) {
  44320. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44321. }
  44322. else {
  44323. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44324. (_this.pinchPrecision *
  44325. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44326. direction);
  44327. }
  44328. previousMultiTouchPanPosition.isPaning = false;
  44329. previousMultiTouchPanPosition.isPinching = true;
  44330. }
  44331. else {
  44332. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44333. if (!previousMultiTouchPanPosition.isPaning) {
  44334. previousMultiTouchPanPosition.isPaning = true;
  44335. previousMultiTouchPanPosition.isPinching = false;
  44336. previousMultiTouchPanPosition.x = ed.x;
  44337. previousMultiTouchPanPosition.y = ed.y;
  44338. return;
  44339. }
  44340. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44341. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44342. }
  44343. }
  44344. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44345. previousMultiTouchPanPosition.x = ed.x;
  44346. previousMultiTouchPanPosition.y = ed.y;
  44347. }
  44348. }
  44349. previousPinchSquaredDistance = pinchSquaredDistance;
  44350. }
  44351. }
  44352. };
  44353. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44354. this._onContextMenu = function (evt) {
  44355. evt.preventDefault();
  44356. };
  44357. if (!this.camera._useCtrlForPanning) {
  44358. element.addEventListener("contextmenu", this._onContextMenu, false);
  44359. }
  44360. this._onLostFocus = function () {
  44361. //this._keys = [];
  44362. pointA = pointB = null;
  44363. previousPinchSquaredDistance = 0;
  44364. previousMultiTouchPanPosition.isPaning = false;
  44365. previousMultiTouchPanPosition.isPinching = false;
  44366. twoFingerActivityCount = 0;
  44367. cacheSoloPointer = null;
  44368. initialDistance = 0;
  44369. };
  44370. this._onMouseMove = function (evt) {
  44371. if (!engine.isPointerLock) {
  44372. return;
  44373. }
  44374. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44375. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44376. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44377. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44378. if (!noPreventDefault) {
  44379. evt.preventDefault();
  44380. }
  44381. };
  44382. this._onGestureStart = function (e) {
  44383. if (window.MSGesture === undefined) {
  44384. return;
  44385. }
  44386. if (!_this._MSGestureHandler) {
  44387. _this._MSGestureHandler = new MSGesture();
  44388. _this._MSGestureHandler.target = element;
  44389. }
  44390. _this._MSGestureHandler.addPointer(e.pointerId);
  44391. };
  44392. this._onGesture = function (e) {
  44393. _this.camera.radius *= e.scale;
  44394. if (e.preventDefault) {
  44395. if (!noPreventDefault) {
  44396. e.stopPropagation();
  44397. e.preventDefault();
  44398. }
  44399. }
  44400. };
  44401. element.addEventListener("mousemove", this._onMouseMove, false);
  44402. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44403. element.addEventListener("MSGestureChange", this._onGesture, false);
  44404. BABYLON.Tools.RegisterTopRootEvents([
  44405. { name: "blur", handler: this._onLostFocus }
  44406. ]);
  44407. };
  44408. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44409. if (this._onLostFocus) {
  44410. BABYLON.Tools.UnregisterTopRootEvents([
  44411. { name: "blur", handler: this._onLostFocus }
  44412. ]);
  44413. }
  44414. if (element && this._observer) {
  44415. this.camera.getScene().onPointerObservable.remove(this._observer);
  44416. this._observer = null;
  44417. if (this._onContextMenu) {
  44418. element.removeEventListener("contextmenu", this._onContextMenu);
  44419. }
  44420. if (this._onMouseMove) {
  44421. element.removeEventListener("mousemove", this._onMouseMove);
  44422. }
  44423. if (this._onGestureStart) {
  44424. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44425. }
  44426. if (this._onGesture) {
  44427. element.removeEventListener("MSGestureChange", this._onGesture);
  44428. }
  44429. this._isPanClick = false;
  44430. this.pinchInwards = true;
  44431. this._onMouseMove = null;
  44432. this._onGestureStart = null;
  44433. this._onGesture = null;
  44434. this._MSGestureHandler = null;
  44435. this._onLostFocus = null;
  44436. this._onContextMenu = null;
  44437. }
  44438. };
  44439. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44440. return "ArcRotateCameraPointersInput";
  44441. };
  44442. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44443. return "pointers";
  44444. };
  44445. __decorate([
  44446. BABYLON.serialize()
  44447. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44448. __decorate([
  44449. BABYLON.serialize()
  44450. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44451. __decorate([
  44452. BABYLON.serialize()
  44453. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44454. __decorate([
  44455. BABYLON.serialize()
  44456. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44457. __decorate([
  44458. BABYLON.serialize()
  44459. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44460. __decorate([
  44461. BABYLON.serialize()
  44462. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44463. __decorate([
  44464. BABYLON.serialize()
  44465. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44466. __decorate([
  44467. BABYLON.serialize()
  44468. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44469. return ArcRotateCameraPointersInput;
  44470. }());
  44471. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44472. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44473. })(BABYLON || (BABYLON = {}));
  44474. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44475. var BABYLON;
  44476. (function (BABYLON) {
  44477. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44478. __extends(ArcRotateCameraInputsManager, _super);
  44479. function ArcRotateCameraInputsManager(camera) {
  44480. return _super.call(this, camera) || this;
  44481. }
  44482. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44483. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44484. return this;
  44485. };
  44486. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44487. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44488. return this;
  44489. };
  44490. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44491. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44492. return this;
  44493. };
  44494. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44495. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44496. return this;
  44497. };
  44498. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44499. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44500. return this;
  44501. };
  44502. return ArcRotateCameraInputsManager;
  44503. }(BABYLON.CameraInputsManager));
  44504. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44505. })(BABYLON || (BABYLON = {}));
  44506. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44507. var BABYLON;
  44508. (function (BABYLON) {
  44509. var ArcRotateCamera = /** @class */ (function (_super) {
  44510. __extends(ArcRotateCamera, _super);
  44511. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44512. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44513. _this.inertialAlphaOffset = 0;
  44514. _this.inertialBetaOffset = 0;
  44515. _this.inertialRadiusOffset = 0;
  44516. _this.lowerAlphaLimit = null;
  44517. _this.upperAlphaLimit = null;
  44518. _this.lowerBetaLimit = 0.01;
  44519. _this.upperBetaLimit = Math.PI;
  44520. _this.lowerRadiusLimit = null;
  44521. _this.upperRadiusLimit = null;
  44522. _this.inertialPanningX = 0;
  44523. _this.inertialPanningY = 0;
  44524. _this.pinchToPanMaxDistance = 20;
  44525. _this.panningDistanceLimit = null;
  44526. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44527. _this.panningInertia = 0.9;
  44528. //-- end properties for backward compatibility for inputs
  44529. _this.zoomOnFactor = 1;
  44530. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44531. _this.allowUpsideDown = true;
  44532. _this._viewMatrix = new BABYLON.Matrix();
  44533. // Panning
  44534. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44535. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44536. _this.checkCollisions = false;
  44537. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44538. _this._previousPosition = BABYLON.Vector3.Zero();
  44539. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44540. _this._newPosition = BABYLON.Vector3.Zero();
  44541. _this._computationVector = BABYLON.Vector3.Zero();
  44542. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44543. if (collidedMesh === void 0) { collidedMesh = null; }
  44544. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44545. newPosition.multiplyInPlace(_this._collider._radius);
  44546. }
  44547. if (!collidedMesh) {
  44548. _this._previousPosition.copyFrom(_this.position);
  44549. }
  44550. else {
  44551. _this.setPosition(newPosition);
  44552. if (_this.onCollide) {
  44553. _this.onCollide(collidedMesh);
  44554. }
  44555. }
  44556. // Recompute because of constraints
  44557. var cosa = Math.cos(_this.alpha);
  44558. var sina = Math.sin(_this.alpha);
  44559. var cosb = Math.cos(_this.beta);
  44560. var sinb = Math.sin(_this.beta);
  44561. if (sinb === 0) {
  44562. sinb = 0.0001;
  44563. }
  44564. var target = _this._getTargetPosition();
  44565. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44566. target.addToRef(_this._computationVector, _this._newPosition);
  44567. _this.position.copyFrom(_this._newPosition);
  44568. var up = _this.upVector;
  44569. if (_this.allowUpsideDown && _this.beta < 0) {
  44570. up = up.clone();
  44571. up = up.negate();
  44572. }
  44573. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44574. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44575. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44576. _this._collisionTriggered = false;
  44577. };
  44578. _this._target = BABYLON.Vector3.Zero();
  44579. if (target) {
  44580. _this.setTarget(target);
  44581. }
  44582. _this.alpha = alpha;
  44583. _this.beta = beta;
  44584. _this.radius = radius;
  44585. _this.getViewMatrix();
  44586. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44587. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44588. return _this;
  44589. }
  44590. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44591. get: function () {
  44592. return this._target;
  44593. },
  44594. set: function (value) {
  44595. this.setTarget(value);
  44596. },
  44597. enumerable: true,
  44598. configurable: true
  44599. });
  44600. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44601. //-- begin properties for backward compatibility for inputs
  44602. get: function () {
  44603. var pointers = this.inputs.attached["pointers"];
  44604. if (pointers)
  44605. return pointers.angularSensibilityX;
  44606. return 0;
  44607. },
  44608. set: function (value) {
  44609. var pointers = this.inputs.attached["pointers"];
  44610. if (pointers) {
  44611. pointers.angularSensibilityX = value;
  44612. }
  44613. },
  44614. enumerable: true,
  44615. configurable: true
  44616. });
  44617. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44618. get: function () {
  44619. var pointers = this.inputs.attached["pointers"];
  44620. if (pointers)
  44621. return pointers.angularSensibilityY;
  44622. return 0;
  44623. },
  44624. set: function (value) {
  44625. var pointers = this.inputs.attached["pointers"];
  44626. if (pointers) {
  44627. pointers.angularSensibilityY = value;
  44628. }
  44629. },
  44630. enumerable: true,
  44631. configurable: true
  44632. });
  44633. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44634. get: function () {
  44635. var pointers = this.inputs.attached["pointers"];
  44636. if (pointers)
  44637. return pointers.pinchPrecision;
  44638. return 0;
  44639. },
  44640. set: function (value) {
  44641. var pointers = this.inputs.attached["pointers"];
  44642. if (pointers) {
  44643. pointers.pinchPrecision = value;
  44644. }
  44645. },
  44646. enumerable: true,
  44647. configurable: true
  44648. });
  44649. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44650. get: function () {
  44651. var pointers = this.inputs.attached["pointers"];
  44652. if (pointers)
  44653. return pointers.pinchDeltaPercentage;
  44654. return 0;
  44655. },
  44656. set: function (value) {
  44657. var pointers = this.inputs.attached["pointers"];
  44658. if (pointers) {
  44659. pointers.pinchDeltaPercentage = value;
  44660. }
  44661. },
  44662. enumerable: true,
  44663. configurable: true
  44664. });
  44665. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44666. get: function () {
  44667. var pointers = this.inputs.attached["pointers"];
  44668. if (pointers)
  44669. return pointers.panningSensibility;
  44670. return 0;
  44671. },
  44672. set: function (value) {
  44673. var pointers = this.inputs.attached["pointers"];
  44674. if (pointers) {
  44675. pointers.panningSensibility = value;
  44676. }
  44677. },
  44678. enumerable: true,
  44679. configurable: true
  44680. });
  44681. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44682. get: function () {
  44683. var keyboard = this.inputs.attached["keyboard"];
  44684. if (keyboard)
  44685. return keyboard.keysUp;
  44686. return [];
  44687. },
  44688. set: function (value) {
  44689. var keyboard = this.inputs.attached["keyboard"];
  44690. if (keyboard)
  44691. keyboard.keysUp = value;
  44692. },
  44693. enumerable: true,
  44694. configurable: true
  44695. });
  44696. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44697. get: function () {
  44698. var keyboard = this.inputs.attached["keyboard"];
  44699. if (keyboard)
  44700. return keyboard.keysDown;
  44701. return [];
  44702. },
  44703. set: function (value) {
  44704. var keyboard = this.inputs.attached["keyboard"];
  44705. if (keyboard)
  44706. keyboard.keysDown = value;
  44707. },
  44708. enumerable: true,
  44709. configurable: true
  44710. });
  44711. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44712. get: function () {
  44713. var keyboard = this.inputs.attached["keyboard"];
  44714. if (keyboard)
  44715. return keyboard.keysLeft;
  44716. return [];
  44717. },
  44718. set: function (value) {
  44719. var keyboard = this.inputs.attached["keyboard"];
  44720. if (keyboard)
  44721. keyboard.keysLeft = value;
  44722. },
  44723. enumerable: true,
  44724. configurable: true
  44725. });
  44726. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44727. get: function () {
  44728. var keyboard = this.inputs.attached["keyboard"];
  44729. if (keyboard)
  44730. return keyboard.keysRight;
  44731. return [];
  44732. },
  44733. set: function (value) {
  44734. var keyboard = this.inputs.attached["keyboard"];
  44735. if (keyboard)
  44736. keyboard.keysRight = value;
  44737. },
  44738. enumerable: true,
  44739. configurable: true
  44740. });
  44741. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44742. get: function () {
  44743. var mousewheel = this.inputs.attached["mousewheel"];
  44744. if (mousewheel)
  44745. return mousewheel.wheelPrecision;
  44746. return 0;
  44747. },
  44748. set: function (value) {
  44749. var mousewheel = this.inputs.attached["mousewheel"];
  44750. if (mousewheel)
  44751. mousewheel.wheelPrecision = value;
  44752. },
  44753. enumerable: true,
  44754. configurable: true
  44755. });
  44756. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44757. get: function () {
  44758. var mousewheel = this.inputs.attached["mousewheel"];
  44759. if (mousewheel)
  44760. return mousewheel.wheelDeltaPercentage;
  44761. return 0;
  44762. },
  44763. set: function (value) {
  44764. var mousewheel = this.inputs.attached["mousewheel"];
  44765. if (mousewheel)
  44766. mousewheel.wheelDeltaPercentage = value;
  44767. },
  44768. enumerable: true,
  44769. configurable: true
  44770. });
  44771. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44772. get: function () {
  44773. return this._bouncingBehavior;
  44774. },
  44775. enumerable: true,
  44776. configurable: true
  44777. });
  44778. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44779. get: function () {
  44780. return this._bouncingBehavior != null;
  44781. },
  44782. set: function (value) {
  44783. if (value === this.useBouncingBehavior) {
  44784. return;
  44785. }
  44786. if (value) {
  44787. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44788. this.addBehavior(this._bouncingBehavior);
  44789. }
  44790. else if (this._bouncingBehavior) {
  44791. this.removeBehavior(this._bouncingBehavior);
  44792. this._bouncingBehavior = null;
  44793. }
  44794. },
  44795. enumerable: true,
  44796. configurable: true
  44797. });
  44798. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44799. get: function () {
  44800. return this._framingBehavior;
  44801. },
  44802. enumerable: true,
  44803. configurable: true
  44804. });
  44805. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44806. get: function () {
  44807. return this._framingBehavior != null;
  44808. },
  44809. set: function (value) {
  44810. if (value === this.useFramingBehavior) {
  44811. return;
  44812. }
  44813. if (value) {
  44814. this._framingBehavior = new BABYLON.FramingBehavior();
  44815. this.addBehavior(this._framingBehavior);
  44816. }
  44817. else if (this._framingBehavior) {
  44818. this.removeBehavior(this._framingBehavior);
  44819. this._framingBehavior = null;
  44820. }
  44821. },
  44822. enumerable: true,
  44823. configurable: true
  44824. });
  44825. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44826. get: function () {
  44827. return this._autoRotationBehavior;
  44828. },
  44829. enumerable: true,
  44830. configurable: true
  44831. });
  44832. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44833. get: function () {
  44834. return this._autoRotationBehavior != null;
  44835. },
  44836. set: function (value) {
  44837. if (value === this.useAutoRotationBehavior) {
  44838. return;
  44839. }
  44840. if (value) {
  44841. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44842. this.addBehavior(this._autoRotationBehavior);
  44843. }
  44844. else if (this._autoRotationBehavior) {
  44845. this.removeBehavior(this._autoRotationBehavior);
  44846. this._autoRotationBehavior = null;
  44847. }
  44848. },
  44849. enumerable: true,
  44850. configurable: true
  44851. });
  44852. // Cache
  44853. ArcRotateCamera.prototype._initCache = function () {
  44854. _super.prototype._initCache.call(this);
  44855. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44856. this._cache.alpha = undefined;
  44857. this._cache.beta = undefined;
  44858. this._cache.radius = undefined;
  44859. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44860. };
  44861. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44862. if (!ignoreParentClass) {
  44863. _super.prototype._updateCache.call(this);
  44864. }
  44865. this._cache._target.copyFrom(this._getTargetPosition());
  44866. this._cache.alpha = this.alpha;
  44867. this._cache.beta = this.beta;
  44868. this._cache.radius = this.radius;
  44869. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44870. };
  44871. ArcRotateCamera.prototype._getTargetPosition = function () {
  44872. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44873. var pos = this._targetHost.getAbsolutePosition();
  44874. if (this._targetBoundingCenter) {
  44875. pos.addToRef(this._targetBoundingCenter, this._target);
  44876. }
  44877. else {
  44878. this._target.copyFrom(pos);
  44879. }
  44880. }
  44881. var lockedTargetPosition = this._getLockedTargetPosition();
  44882. if (lockedTargetPosition) {
  44883. return lockedTargetPosition;
  44884. }
  44885. return this._target;
  44886. };
  44887. ArcRotateCamera.prototype.storeState = function () {
  44888. this._storedAlpha = this.alpha;
  44889. this._storedBeta = this.beta;
  44890. this._storedRadius = this.radius;
  44891. this._storedTarget = this._getTargetPosition().clone();
  44892. return _super.prototype.storeState.call(this);
  44893. };
  44894. /**
  44895. * Restored camera state. You must call storeState() first
  44896. */
  44897. ArcRotateCamera.prototype._restoreStateValues = function () {
  44898. if (!_super.prototype._restoreStateValues.call(this)) {
  44899. return false;
  44900. }
  44901. this.alpha = this._storedAlpha;
  44902. this.beta = this._storedBeta;
  44903. this.radius = this._storedRadius;
  44904. this.setTarget(this._storedTarget.clone());
  44905. this.inertialAlphaOffset = 0;
  44906. this.inertialBetaOffset = 0;
  44907. this.inertialRadiusOffset = 0;
  44908. this.inertialPanningX = 0;
  44909. this.inertialPanningY = 0;
  44910. return true;
  44911. };
  44912. // Synchronized
  44913. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44914. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44915. return false;
  44916. return this._cache._target.equals(this._getTargetPosition())
  44917. && this._cache.alpha === this.alpha
  44918. && this._cache.beta === this.beta
  44919. && this._cache.radius === this.radius
  44920. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44921. };
  44922. // Methods
  44923. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44924. var _this = this;
  44925. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44926. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44927. this._useCtrlForPanning = useCtrlForPanning;
  44928. this._panningMouseButton = panningMouseButton;
  44929. this.inputs.attachElement(element, noPreventDefault);
  44930. this._reset = function () {
  44931. _this.inertialAlphaOffset = 0;
  44932. _this.inertialBetaOffset = 0;
  44933. _this.inertialRadiusOffset = 0;
  44934. _this.inertialPanningX = 0;
  44935. _this.inertialPanningY = 0;
  44936. };
  44937. };
  44938. ArcRotateCamera.prototype.detachControl = function (element) {
  44939. this.inputs.detachElement(element);
  44940. if (this._reset) {
  44941. this._reset();
  44942. }
  44943. };
  44944. ArcRotateCamera.prototype._checkInputs = function () {
  44945. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44946. if (this._collisionTriggered) {
  44947. return;
  44948. }
  44949. this.inputs.checkInputs();
  44950. // Inertia
  44951. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44952. if (this.getScene().useRightHandedSystem) {
  44953. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44954. }
  44955. else {
  44956. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44957. }
  44958. this.beta += this.inertialBetaOffset;
  44959. this.radius -= this.inertialRadiusOffset;
  44960. this.inertialAlphaOffset *= this.inertia;
  44961. this.inertialBetaOffset *= this.inertia;
  44962. this.inertialRadiusOffset *= this.inertia;
  44963. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44964. this.inertialAlphaOffset = 0;
  44965. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44966. this.inertialBetaOffset = 0;
  44967. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44968. this.inertialRadiusOffset = 0;
  44969. }
  44970. // Panning inertia
  44971. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44972. if (!this._localDirection) {
  44973. this._localDirection = BABYLON.Vector3.Zero();
  44974. this._transformedDirection = BABYLON.Vector3.Zero();
  44975. }
  44976. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44977. this._localDirection.multiplyInPlace(this.panningAxis);
  44978. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44979. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44980. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44981. if (!this.panningAxis.y) {
  44982. this._transformedDirection.y = 0;
  44983. }
  44984. if (!this._targetHost) {
  44985. if (this.panningDistanceLimit) {
  44986. this._transformedDirection.addInPlace(this._target);
  44987. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44988. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44989. this._target.copyFrom(this._transformedDirection);
  44990. }
  44991. }
  44992. else {
  44993. this._target.addInPlace(this._transformedDirection);
  44994. }
  44995. }
  44996. this.inertialPanningX *= this.panningInertia;
  44997. this.inertialPanningY *= this.panningInertia;
  44998. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44999. this.inertialPanningX = 0;
  45000. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45001. this.inertialPanningY = 0;
  45002. }
  45003. // Limits
  45004. this._checkLimits();
  45005. _super.prototype._checkInputs.call(this);
  45006. };
  45007. ArcRotateCamera.prototype._checkLimits = function () {
  45008. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45009. if (this.allowUpsideDown && this.beta > Math.PI) {
  45010. this.beta = this.beta - (2 * Math.PI);
  45011. }
  45012. }
  45013. else {
  45014. if (this.beta < this.lowerBetaLimit) {
  45015. this.beta = this.lowerBetaLimit;
  45016. }
  45017. }
  45018. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45019. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45020. this.beta = this.beta + (2 * Math.PI);
  45021. }
  45022. }
  45023. else {
  45024. if (this.beta > this.upperBetaLimit) {
  45025. this.beta = this.upperBetaLimit;
  45026. }
  45027. }
  45028. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45029. this.alpha = this.lowerAlphaLimit;
  45030. }
  45031. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45032. this.alpha = this.upperAlphaLimit;
  45033. }
  45034. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45035. this.radius = this.lowerRadiusLimit;
  45036. }
  45037. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45038. this.radius = this.upperRadiusLimit;
  45039. }
  45040. };
  45041. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45042. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45043. this.radius = this._computationVector.length();
  45044. if (this.radius === 0) {
  45045. this.radius = 0.0001; // Just to avoid division by zero
  45046. }
  45047. // Alpha
  45048. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45049. if (this._computationVector.z < 0) {
  45050. this.alpha = 2 * Math.PI - this.alpha;
  45051. }
  45052. // Beta
  45053. this.beta = Math.acos(this._computationVector.y / this.radius);
  45054. this._checkLimits();
  45055. };
  45056. ArcRotateCamera.prototype.setPosition = function (position) {
  45057. if (this.position.equals(position)) {
  45058. return;
  45059. }
  45060. this.position.copyFrom(position);
  45061. this.rebuildAnglesAndRadius();
  45062. };
  45063. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45064. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45065. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45066. if (target.getBoundingInfo) {
  45067. if (toBoundingCenter) {
  45068. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45069. }
  45070. else {
  45071. this._targetBoundingCenter = null;
  45072. }
  45073. this._targetHost = target;
  45074. this._target = this._getTargetPosition();
  45075. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45076. }
  45077. else {
  45078. var newTarget = target;
  45079. var currentTarget = this._getTargetPosition();
  45080. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45081. return;
  45082. }
  45083. this._targetHost = null;
  45084. this._target = newTarget;
  45085. this._targetBoundingCenter = null;
  45086. this.onMeshTargetChangedObservable.notifyObservers(null);
  45087. }
  45088. this.rebuildAnglesAndRadius();
  45089. };
  45090. ArcRotateCamera.prototype._getViewMatrix = function () {
  45091. // Compute
  45092. var cosa = Math.cos(this.alpha);
  45093. var sina = Math.sin(this.alpha);
  45094. var cosb = Math.cos(this.beta);
  45095. var sinb = Math.sin(this.beta);
  45096. if (sinb === 0) {
  45097. sinb = 0.0001;
  45098. }
  45099. var target = this._getTargetPosition();
  45100. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45101. target.addToRef(this._computationVector, this._newPosition);
  45102. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45103. if (!this._collider) {
  45104. this._collider = new BABYLON.Collider();
  45105. }
  45106. this._collider._radius = this.collisionRadius;
  45107. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45108. this._collisionTriggered = true;
  45109. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45110. }
  45111. else {
  45112. this.position.copyFrom(this._newPosition);
  45113. var up = this.upVector;
  45114. if (this.allowUpsideDown && sinb < 0) {
  45115. up = up.clone();
  45116. up = up.negate();
  45117. }
  45118. if (this.getScene().useRightHandedSystem) {
  45119. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45120. }
  45121. else {
  45122. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45123. }
  45124. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45125. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45126. }
  45127. this._currentTarget = target;
  45128. return this._viewMatrix;
  45129. };
  45130. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45131. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45132. meshes = meshes || this.getScene().meshes;
  45133. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45134. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45135. this.radius = distance * this.zoomOnFactor;
  45136. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45137. };
  45138. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45139. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45140. var meshesOrMinMaxVector;
  45141. var distance;
  45142. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45143. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45144. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45145. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45146. }
  45147. else {
  45148. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45149. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45150. distance = minMaxVectorAndDistance.distance;
  45151. }
  45152. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45153. if (!doNotUpdateMaxZ) {
  45154. this.maxZ = distance * 2;
  45155. }
  45156. };
  45157. /**
  45158. * @override
  45159. * Override Camera.createRigCamera
  45160. */
  45161. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45162. var alphaShift = 0;
  45163. switch (this.cameraRigMode) {
  45164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45166. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45167. case BABYLON.Camera.RIG_MODE_VR:
  45168. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45169. break;
  45170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45171. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45172. break;
  45173. }
  45174. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45175. rigCam._cameraRigParams = {};
  45176. return rigCam;
  45177. };
  45178. /**
  45179. * @override
  45180. * Override Camera._updateRigCameras
  45181. */
  45182. ArcRotateCamera.prototype._updateRigCameras = function () {
  45183. var camLeft = this._rigCameras[0];
  45184. var camRight = this._rigCameras[1];
  45185. camLeft.beta = camRight.beta = this.beta;
  45186. camLeft.radius = camRight.radius = this.radius;
  45187. switch (this.cameraRigMode) {
  45188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45190. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45191. case BABYLON.Camera.RIG_MODE_VR:
  45192. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45193. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45194. break;
  45195. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45196. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45197. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45198. break;
  45199. }
  45200. _super.prototype._updateRigCameras.call(this);
  45201. };
  45202. ArcRotateCamera.prototype.dispose = function () {
  45203. this.inputs.clear();
  45204. _super.prototype.dispose.call(this);
  45205. };
  45206. ArcRotateCamera.prototype.getClassName = function () {
  45207. return "ArcRotateCamera";
  45208. };
  45209. __decorate([
  45210. BABYLON.serialize()
  45211. ], ArcRotateCamera.prototype, "alpha", void 0);
  45212. __decorate([
  45213. BABYLON.serialize()
  45214. ], ArcRotateCamera.prototype, "beta", void 0);
  45215. __decorate([
  45216. BABYLON.serialize()
  45217. ], ArcRotateCamera.prototype, "radius", void 0);
  45218. __decorate([
  45219. BABYLON.serializeAsVector3("target")
  45220. ], ArcRotateCamera.prototype, "_target", void 0);
  45221. __decorate([
  45222. BABYLON.serialize()
  45223. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45224. __decorate([
  45225. BABYLON.serialize()
  45226. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45227. __decorate([
  45228. BABYLON.serialize()
  45229. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45230. __decorate([
  45231. BABYLON.serialize()
  45232. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45233. __decorate([
  45234. BABYLON.serialize()
  45235. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45236. __decorate([
  45237. BABYLON.serialize()
  45238. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45239. __decorate([
  45240. BABYLON.serialize()
  45241. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45242. __decorate([
  45243. BABYLON.serialize()
  45244. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45245. __decorate([
  45246. BABYLON.serialize()
  45247. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45248. __decorate([
  45249. BABYLON.serialize()
  45250. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45251. __decorate([
  45252. BABYLON.serialize()
  45253. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45254. __decorate([
  45255. BABYLON.serialize()
  45256. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45257. __decorate([
  45258. BABYLON.serialize()
  45259. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45260. __decorate([
  45261. BABYLON.serializeAsVector3()
  45262. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45263. __decorate([
  45264. BABYLON.serialize()
  45265. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45266. __decorate([
  45267. BABYLON.serialize()
  45268. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45269. __decorate([
  45270. BABYLON.serialize()
  45271. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45272. return ArcRotateCamera;
  45273. }(BABYLON.TargetCamera));
  45274. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45275. })(BABYLON || (BABYLON = {}));
  45276. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45277. var BABYLON;
  45278. (function (BABYLON) {
  45279. /**
  45280. * The HemisphericLight simulates the ambient environment light,
  45281. * so the passed direction is the light reflection direction, not the incoming direction.
  45282. */
  45283. var HemisphericLight = /** @class */ (function (_super) {
  45284. __extends(HemisphericLight, _super);
  45285. /**
  45286. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45287. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45288. * The HemisphericLight can't cast shadows.
  45289. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45290. * @param name The friendly name of the light
  45291. * @param direction The direction of the light reflection
  45292. * @param scene The scene the light belongs to
  45293. */
  45294. function HemisphericLight(name, direction, scene) {
  45295. var _this = _super.call(this, name, scene) || this;
  45296. /**
  45297. * The groundColor is the light in the opposite direction to the one specified during creation.
  45298. * 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.
  45299. */
  45300. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45301. _this.direction = direction || BABYLON.Vector3.Up();
  45302. return _this;
  45303. }
  45304. HemisphericLight.prototype._buildUniformLayout = function () {
  45305. this._uniformBuffer.addUniform("vLightData", 4);
  45306. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45307. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45308. this._uniformBuffer.addUniform("vLightGround", 3);
  45309. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45310. this._uniformBuffer.addUniform("depthValues", 2);
  45311. this._uniformBuffer.create();
  45312. };
  45313. /**
  45314. * Returns the string "HemisphericLight".
  45315. * @return The class name
  45316. */
  45317. HemisphericLight.prototype.getClassName = function () {
  45318. return "HemisphericLight";
  45319. };
  45320. /**
  45321. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45322. * Returns the updated direction.
  45323. * @param target The target the direction should point to
  45324. * @return The computed direction
  45325. */
  45326. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45327. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45328. return this.direction;
  45329. };
  45330. /**
  45331. * Returns the shadow generator associated to the light.
  45332. * @returns Always null for hemispheric lights because it does not support shadows.
  45333. */
  45334. HemisphericLight.prototype.getShadowGenerator = function () {
  45335. return null;
  45336. };
  45337. /**
  45338. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45339. * @param effect The effect to update
  45340. * @param lightIndex The index of the light in the effect to update
  45341. * @returns The hemispheric light
  45342. */
  45343. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45344. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45345. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45346. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45347. return this;
  45348. };
  45349. /**
  45350. * @ignore internal use only.
  45351. */
  45352. HemisphericLight.prototype._getWorldMatrix = function () {
  45353. if (!this._worldMatrix) {
  45354. this._worldMatrix = BABYLON.Matrix.Identity();
  45355. }
  45356. return this._worldMatrix;
  45357. };
  45358. /**
  45359. * Returns the integer 3.
  45360. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45361. */
  45362. HemisphericLight.prototype.getTypeID = function () {
  45363. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45364. };
  45365. __decorate([
  45366. BABYLON.serializeAsColor3()
  45367. ], HemisphericLight.prototype, "groundColor", void 0);
  45368. __decorate([
  45369. BABYLON.serializeAsVector3()
  45370. ], HemisphericLight.prototype, "direction", void 0);
  45371. return HemisphericLight;
  45372. }(BABYLON.Light));
  45373. BABYLON.HemisphericLight = HemisphericLight;
  45374. })(BABYLON || (BABYLON = {}));
  45375. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45376. var BABYLON;
  45377. (function (BABYLON) {
  45378. /**
  45379. * Base implementation of @see IShadowLight
  45380. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45381. */
  45382. var ShadowLight = /** @class */ (function (_super) {
  45383. __extends(ShadowLight, _super);
  45384. function ShadowLight() {
  45385. var _this = _super !== null && _super.apply(this, arguments) || this;
  45386. _this._needProjectionMatrixCompute = true;
  45387. return _this;
  45388. }
  45389. ShadowLight.prototype._setPosition = function (value) {
  45390. this._position = value;
  45391. };
  45392. Object.defineProperty(ShadowLight.prototype, "position", {
  45393. /**
  45394. * Sets the position the shadow will be casted from. Also use as the light position for both
  45395. * point and spot lights.
  45396. */
  45397. get: function () {
  45398. return this._position;
  45399. },
  45400. /**
  45401. * Sets the position the shadow will be casted from. Also use as the light position for both
  45402. * point and spot lights.
  45403. */
  45404. set: function (value) {
  45405. this._setPosition(value);
  45406. },
  45407. enumerable: true,
  45408. configurable: true
  45409. });
  45410. ShadowLight.prototype._setDirection = function (value) {
  45411. this._direction = value;
  45412. };
  45413. Object.defineProperty(ShadowLight.prototype, "direction", {
  45414. /**
  45415. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45416. * Also use as the light direction on spot and directional lights.
  45417. */
  45418. get: function () {
  45419. return this._direction;
  45420. },
  45421. /**
  45422. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45423. * Also use as the light direction on spot and directional lights.
  45424. */
  45425. set: function (value) {
  45426. this._setDirection(value);
  45427. },
  45428. enumerable: true,
  45429. configurable: true
  45430. });
  45431. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45432. /**
  45433. * Gets the shadow projection clipping minimum z value.
  45434. */
  45435. get: function () {
  45436. return this._shadowMinZ;
  45437. },
  45438. /**
  45439. * Sets the shadow projection clipping minimum z value.
  45440. */
  45441. set: function (value) {
  45442. this._shadowMinZ = value;
  45443. this.forceProjectionMatrixCompute();
  45444. },
  45445. enumerable: true,
  45446. configurable: true
  45447. });
  45448. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45449. /**
  45450. * Sets the shadow projection clipping maximum z value.
  45451. */
  45452. get: function () {
  45453. return this._shadowMaxZ;
  45454. },
  45455. /**
  45456. * Gets the shadow projection clipping maximum z value.
  45457. */
  45458. set: function (value) {
  45459. this._shadowMaxZ = value;
  45460. this.forceProjectionMatrixCompute();
  45461. },
  45462. enumerable: true,
  45463. configurable: true
  45464. });
  45465. /**
  45466. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45467. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45468. */
  45469. ShadowLight.prototype.computeTransformedInformation = function () {
  45470. if (this.parent && this.parent.getWorldMatrix) {
  45471. if (!this.transformedPosition) {
  45472. this.transformedPosition = BABYLON.Vector3.Zero();
  45473. }
  45474. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45475. // In case the direction is present.
  45476. if (this.direction) {
  45477. if (!this.transformedDirection) {
  45478. this.transformedDirection = BABYLON.Vector3.Zero();
  45479. }
  45480. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45481. }
  45482. return true;
  45483. }
  45484. return false;
  45485. };
  45486. /**
  45487. * Return the depth scale used for the shadow map.
  45488. * @returns the depth scale.
  45489. */
  45490. ShadowLight.prototype.getDepthScale = function () {
  45491. return 50.0;
  45492. };
  45493. /**
  45494. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45495. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45496. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45497. */
  45498. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45499. return this.transformedDirection ? this.transformedDirection : this.direction;
  45500. };
  45501. /**
  45502. * Returns the ShadowLight absolute position in the World.
  45503. * @returns the position vector in world space
  45504. */
  45505. ShadowLight.prototype.getAbsolutePosition = function () {
  45506. return this.transformedPosition ? this.transformedPosition : this.position;
  45507. };
  45508. /**
  45509. * Sets the ShadowLight direction toward the passed target.
  45510. * @param target The point tot target in local space
  45511. * @returns the updated ShadowLight direction
  45512. */
  45513. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45514. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45515. return this.direction;
  45516. };
  45517. /**
  45518. * Returns the light rotation in euler definition.
  45519. * @returns the x y z rotation in local space.
  45520. */
  45521. ShadowLight.prototype.getRotation = function () {
  45522. this.direction.normalize();
  45523. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45524. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45525. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45526. };
  45527. /**
  45528. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45529. * @returns true if a cube texture needs to be use
  45530. */
  45531. ShadowLight.prototype.needCube = function () {
  45532. return false;
  45533. };
  45534. /**
  45535. * Detects if the projection matrix requires to be recomputed this frame.
  45536. * @returns true if it requires to be recomputed otherwise, false.
  45537. */
  45538. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45539. return this._needProjectionMatrixCompute;
  45540. };
  45541. /**
  45542. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45543. */
  45544. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45545. this._needProjectionMatrixCompute = true;
  45546. };
  45547. /**
  45548. * Get the world matrix of the sahdow lights.
  45549. * @ignore Internal Use Only
  45550. */
  45551. ShadowLight.prototype._getWorldMatrix = function () {
  45552. if (!this._worldMatrix) {
  45553. this._worldMatrix = BABYLON.Matrix.Identity();
  45554. }
  45555. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45556. return this._worldMatrix;
  45557. };
  45558. /**
  45559. * Gets the minZ used for shadow according to both the scene and the light.
  45560. * @param activeCamera The camera we are returning the min for
  45561. * @returns the depth min z
  45562. */
  45563. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45564. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45565. };
  45566. /**
  45567. * Gets the maxZ used for shadow according to both the scene and the light.
  45568. * @param activeCamera The camera we are returning the max for
  45569. * @returns the depth max z
  45570. */
  45571. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45572. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45573. };
  45574. /**
  45575. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45576. * @param matrix The materix to updated with the projection information
  45577. * @param viewMatrix The transform matrix of the light
  45578. * @param renderList The list of mesh to render in the map
  45579. * @returns The current light
  45580. */
  45581. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45582. if (this.customProjectionMatrixBuilder) {
  45583. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45584. }
  45585. else {
  45586. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45587. }
  45588. return this;
  45589. };
  45590. __decorate([
  45591. BABYLON.serializeAsVector3()
  45592. ], ShadowLight.prototype, "position", null);
  45593. __decorate([
  45594. BABYLON.serializeAsVector3()
  45595. ], ShadowLight.prototype, "direction", null);
  45596. __decorate([
  45597. BABYLON.serialize()
  45598. ], ShadowLight.prototype, "shadowMinZ", null);
  45599. __decorate([
  45600. BABYLON.serialize()
  45601. ], ShadowLight.prototype, "shadowMaxZ", null);
  45602. return ShadowLight;
  45603. }(BABYLON.Light));
  45604. BABYLON.ShadowLight = ShadowLight;
  45605. })(BABYLON || (BABYLON = {}));
  45606. //# sourceMappingURL=babylon.shadowLight.js.map
  45607. var BABYLON;
  45608. (function (BABYLON) {
  45609. /**
  45610. * A point light is a light defined by an unique point in world space.
  45611. * The light is emitted in every direction from this point.
  45612. * A good example of a point light is a standard light bulb.
  45613. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45614. */
  45615. var PointLight = /** @class */ (function (_super) {
  45616. __extends(PointLight, _super);
  45617. /**
  45618. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45619. * A PointLight emits the light in every direction.
  45620. * It can cast shadows.
  45621. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45622. * ```javascript
  45623. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45624. * ```
  45625. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45626. * @param name The light friendly name
  45627. * @param position The position of the point light in the scene
  45628. * @param scene The scene the lights belongs to
  45629. */
  45630. function PointLight(name, position, scene) {
  45631. var _this = _super.call(this, name, scene) || this;
  45632. _this._shadowAngle = Math.PI / 2;
  45633. _this.position = position;
  45634. return _this;
  45635. }
  45636. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45637. /**
  45638. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45639. * This specifies what angle the shadow will use to be created.
  45640. *
  45641. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45642. */
  45643. get: function () {
  45644. return this._shadowAngle;
  45645. },
  45646. /**
  45647. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45648. * This specifies what angle the shadow will use to be created.
  45649. *
  45650. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45651. */
  45652. set: function (value) {
  45653. this._shadowAngle = value;
  45654. this.forceProjectionMatrixCompute();
  45655. },
  45656. enumerable: true,
  45657. configurable: true
  45658. });
  45659. Object.defineProperty(PointLight.prototype, "direction", {
  45660. /**
  45661. * Gets the direction if it has been set.
  45662. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45663. */
  45664. get: function () {
  45665. return this._direction;
  45666. },
  45667. /**
  45668. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45669. */
  45670. set: function (value) {
  45671. var previousNeedCube = this.needCube();
  45672. this._direction = value;
  45673. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45674. this._shadowGenerator.recreateShadowMap();
  45675. }
  45676. },
  45677. enumerable: true,
  45678. configurable: true
  45679. });
  45680. /**
  45681. * Returns the string "PointLight"
  45682. * @returns the class name
  45683. */
  45684. PointLight.prototype.getClassName = function () {
  45685. return "PointLight";
  45686. };
  45687. /**
  45688. * Returns the integer 0.
  45689. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45690. */
  45691. PointLight.prototype.getTypeID = function () {
  45692. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45693. };
  45694. /**
  45695. * Specifies wether or not the shadowmap should be a cube texture.
  45696. * @returns true if the shadowmap needs to be a cube texture.
  45697. */
  45698. PointLight.prototype.needCube = function () {
  45699. return !this.direction;
  45700. };
  45701. /**
  45702. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45703. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45704. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45705. */
  45706. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45707. if (this.direction) {
  45708. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45709. }
  45710. else {
  45711. switch (faceIndex) {
  45712. case 0:
  45713. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45714. case 1:
  45715. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45716. case 2:
  45717. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45718. case 3:
  45719. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45720. case 4:
  45721. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45722. case 5:
  45723. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45724. }
  45725. }
  45726. return BABYLON.Vector3.Zero();
  45727. };
  45728. /**
  45729. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45730. * - fov = PI / 2
  45731. * - aspect ratio : 1.0
  45732. * - z-near and far equal to the active camera minZ and maxZ.
  45733. * Returns the PointLight.
  45734. */
  45735. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45736. var activeCamera = this.getScene().activeCamera;
  45737. if (!activeCamera) {
  45738. return;
  45739. }
  45740. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45741. };
  45742. PointLight.prototype._buildUniformLayout = function () {
  45743. this._uniformBuffer.addUniform("vLightData", 4);
  45744. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45745. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45746. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45747. this._uniformBuffer.addUniform("depthValues", 2);
  45748. this._uniformBuffer.create();
  45749. };
  45750. /**
  45751. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45752. * @param effect The effect to update
  45753. * @param lightIndex The index of the light in the effect to update
  45754. * @returns The point light
  45755. */
  45756. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45757. if (this.computeTransformedInformation()) {
  45758. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45759. return this;
  45760. }
  45761. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45762. return this;
  45763. };
  45764. __decorate([
  45765. BABYLON.serialize()
  45766. ], PointLight.prototype, "shadowAngle", null);
  45767. return PointLight;
  45768. }(BABYLON.ShadowLight));
  45769. BABYLON.PointLight = PointLight;
  45770. })(BABYLON || (BABYLON = {}));
  45771. //# sourceMappingURL=babylon.pointLight.js.map
  45772. var BABYLON;
  45773. (function (BABYLON) {
  45774. /**
  45775. * A directional light is defined by a direction (what a surprise!).
  45776. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45777. * 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.
  45778. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45779. */
  45780. var DirectionalLight = /** @class */ (function (_super) {
  45781. __extends(DirectionalLight, _super);
  45782. /**
  45783. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45784. * The directional light is emitted from everywhere in the given direction.
  45785. * It can cast shawdows.
  45786. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45787. * @param name The friendly name of the light
  45788. * @param direction The direction of the light
  45789. * @param scene The scene the light belongs to
  45790. */
  45791. function DirectionalLight(name, direction, scene) {
  45792. var _this = _super.call(this, name, scene) || this;
  45793. _this._shadowFrustumSize = 0;
  45794. _this._shadowOrthoScale = 0.5;
  45795. /**
  45796. * Automatically compute the projection matrix to best fit (including all the casters)
  45797. * on each frame.
  45798. */
  45799. _this.autoUpdateExtends = true;
  45800. // Cache
  45801. _this._orthoLeft = Number.MAX_VALUE;
  45802. _this._orthoRight = Number.MIN_VALUE;
  45803. _this._orthoTop = Number.MIN_VALUE;
  45804. _this._orthoBottom = Number.MAX_VALUE;
  45805. _this.position = direction.scale(-1.0);
  45806. _this.direction = direction;
  45807. return _this;
  45808. }
  45809. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45810. /**
  45811. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45812. */
  45813. get: function () {
  45814. return this._shadowFrustumSize;
  45815. },
  45816. /**
  45817. * Specifies a fix frustum size for the shadow generation.
  45818. */
  45819. set: function (value) {
  45820. this._shadowFrustumSize = value;
  45821. this.forceProjectionMatrixCompute();
  45822. },
  45823. enumerable: true,
  45824. configurable: true
  45825. });
  45826. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45827. /**
  45828. * Gets the shadow projection scale against the optimal computed one.
  45829. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45830. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45831. */
  45832. get: function () {
  45833. return this._shadowOrthoScale;
  45834. },
  45835. /**
  45836. * Sets the shadow projection scale against the optimal computed one.
  45837. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45838. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45839. */
  45840. set: function (value) {
  45841. this._shadowOrthoScale = value;
  45842. this.forceProjectionMatrixCompute();
  45843. },
  45844. enumerable: true,
  45845. configurable: true
  45846. });
  45847. /**
  45848. * Returns the string "DirectionalLight".
  45849. * @return The class name
  45850. */
  45851. DirectionalLight.prototype.getClassName = function () {
  45852. return "DirectionalLight";
  45853. };
  45854. /**
  45855. * Returns the integer 1.
  45856. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45857. */
  45858. DirectionalLight.prototype.getTypeID = function () {
  45859. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45860. };
  45861. /**
  45862. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45863. * Returns the DirectionalLight Shadow projection matrix.
  45864. */
  45865. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45866. if (this.shadowFrustumSize > 0) {
  45867. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45868. }
  45869. else {
  45870. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45871. }
  45872. };
  45873. /**
  45874. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45875. * Returns the DirectionalLight Shadow projection matrix.
  45876. */
  45877. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45878. var activeCamera = this.getScene().activeCamera;
  45879. if (!activeCamera) {
  45880. return;
  45881. }
  45882. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45883. };
  45884. /**
  45885. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45886. * Returns the DirectionalLight Shadow projection matrix.
  45887. */
  45888. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45889. var activeCamera = this.getScene().activeCamera;
  45890. if (!activeCamera) {
  45891. return;
  45892. }
  45893. // Check extends
  45894. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45895. var tempVector3 = BABYLON.Vector3.Zero();
  45896. this._orthoLeft = Number.MAX_VALUE;
  45897. this._orthoRight = Number.MIN_VALUE;
  45898. this._orthoTop = Number.MIN_VALUE;
  45899. this._orthoBottom = Number.MAX_VALUE;
  45900. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45901. var mesh = renderList[meshIndex];
  45902. if (!mesh) {
  45903. continue;
  45904. }
  45905. var boundingInfo = mesh.getBoundingInfo();
  45906. var boundingBox = boundingInfo.boundingBox;
  45907. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45908. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45909. if (tempVector3.x < this._orthoLeft)
  45910. this._orthoLeft = tempVector3.x;
  45911. if (tempVector3.y < this._orthoBottom)
  45912. this._orthoBottom = tempVector3.y;
  45913. if (tempVector3.x > this._orthoRight)
  45914. this._orthoRight = tempVector3.x;
  45915. if (tempVector3.y > this._orthoTop)
  45916. this._orthoTop = tempVector3.y;
  45917. }
  45918. }
  45919. }
  45920. var xOffset = this._orthoRight - this._orthoLeft;
  45921. var yOffset = this._orthoTop - this._orthoBottom;
  45922. 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);
  45923. };
  45924. DirectionalLight.prototype._buildUniformLayout = function () {
  45925. this._uniformBuffer.addUniform("vLightData", 4);
  45926. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45927. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45928. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45929. this._uniformBuffer.addUniform("depthValues", 2);
  45930. this._uniformBuffer.create();
  45931. };
  45932. /**
  45933. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45934. * @param effect The effect to update
  45935. * @param lightIndex The index of the light in the effect to update
  45936. * @returns The directional light
  45937. */
  45938. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45939. if (this.computeTransformedInformation()) {
  45940. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45941. return this;
  45942. }
  45943. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45944. return this;
  45945. };
  45946. /**
  45947. * Gets the minZ used for shadow according to both the scene and the light.
  45948. *
  45949. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45950. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45951. * @param activeCamera The camera we are returning the min for
  45952. * @returns the depth min z
  45953. */
  45954. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45955. return 1;
  45956. };
  45957. /**
  45958. * Gets the maxZ used for shadow according to both the scene and the light.
  45959. *
  45960. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45961. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45962. * @param activeCamera The camera we are returning the max for
  45963. * @returns the depth max z
  45964. */
  45965. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45966. return 1;
  45967. };
  45968. __decorate([
  45969. BABYLON.serialize()
  45970. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45971. __decorate([
  45972. BABYLON.serialize()
  45973. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45974. __decorate([
  45975. BABYLON.serialize()
  45976. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45977. return DirectionalLight;
  45978. }(BABYLON.ShadowLight));
  45979. BABYLON.DirectionalLight = DirectionalLight;
  45980. })(BABYLON || (BABYLON = {}));
  45981. //# sourceMappingURL=babylon.directionalLight.js.map
  45982. var BABYLON;
  45983. (function (BABYLON) {
  45984. /**
  45985. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45986. * These values define a cone of light starting from the position, emitting toward the direction.
  45987. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45988. * and the exponent defines the speed of the decay of the light with distance (reach).
  45989. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45990. */
  45991. var SpotLight = /** @class */ (function (_super) {
  45992. __extends(SpotLight, _super);
  45993. /**
  45994. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45995. * It can cast shadows.
  45996. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45997. * @param name The light friendly name
  45998. * @param position The position of the spot light in the scene
  45999. * @param direction The direction of the light in the scene
  46000. * @param angle The cone angle of the light in Radians
  46001. * @param exponent The light decay speed with the distance from the emission spot
  46002. * @param scene The scene the lights belongs to
  46003. */
  46004. function SpotLight(name, position, direction, angle, exponent, scene) {
  46005. var _this = _super.call(this, name, scene) || this;
  46006. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46007. _this._projectionTextureLightNear = 1e-6;
  46008. _this._projectionTextureLightFar = 1000.0;
  46009. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46010. _this._projectionTextureViewLightDirty = true;
  46011. _this._projectionTextureProjectionLightDirty = true;
  46012. _this._projectionTextureDirty = true;
  46013. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46014. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46015. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46016. _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);
  46017. _this.position = position;
  46018. _this.direction = direction;
  46019. _this.angle = angle;
  46020. _this.exponent = exponent;
  46021. return _this;
  46022. }
  46023. Object.defineProperty(SpotLight.prototype, "angle", {
  46024. /**
  46025. * Gets the cone angle of the spot light in Radians.
  46026. */
  46027. get: function () {
  46028. return this._angle;
  46029. },
  46030. /**
  46031. * Sets the cone angle of the spot light in Radians.
  46032. */
  46033. set: function (value) {
  46034. this._angle = value;
  46035. this._projectionTextureProjectionLightDirty = true;
  46036. this.forceProjectionMatrixCompute();
  46037. },
  46038. enumerable: true,
  46039. configurable: true
  46040. });
  46041. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46042. /**
  46043. * Allows scaling the angle of the light for shadow generation only.
  46044. */
  46045. get: function () {
  46046. return this._shadowAngleScale;
  46047. },
  46048. /**
  46049. * Allows scaling the angle of the light for shadow generation only.
  46050. */
  46051. set: function (value) {
  46052. this._shadowAngleScale = value;
  46053. this.forceProjectionMatrixCompute();
  46054. },
  46055. enumerable: true,
  46056. configurable: true
  46057. });
  46058. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46059. /**
  46060. * Allows reading the projecton texture
  46061. */
  46062. get: function () {
  46063. return this._projectionTextureMatrix;
  46064. },
  46065. enumerable: true,
  46066. configurable: true
  46067. });
  46068. ;
  46069. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46070. /**
  46071. * Gets the near clip of the Spotlight for texture projection.
  46072. */
  46073. get: function () {
  46074. return this._projectionTextureLightNear;
  46075. },
  46076. /**
  46077. * Sets the near clip of the Spotlight for texture projection.
  46078. */
  46079. set: function (value) {
  46080. this._projectionTextureLightNear = value;
  46081. this._projectionTextureProjectionLightDirty = true;
  46082. },
  46083. enumerable: true,
  46084. configurable: true
  46085. });
  46086. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46087. /**
  46088. * Gets the far clip of the Spotlight for texture projection.
  46089. */
  46090. get: function () {
  46091. return this._projectionTextureLightFar;
  46092. },
  46093. /**
  46094. * Sets the far clip of the Spotlight for texture projection.
  46095. */
  46096. set: function (value) {
  46097. this._projectionTextureLightFar = value;
  46098. this._projectionTextureProjectionLightDirty = true;
  46099. },
  46100. enumerable: true,
  46101. configurable: true
  46102. });
  46103. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46104. /**
  46105. * Gets the Up vector of the Spotlight for texture projection.
  46106. */
  46107. get: function () {
  46108. return this._projectionTextureUpDirection;
  46109. },
  46110. /**
  46111. * Sets the Up vector of the Spotlight for texture projection.
  46112. */
  46113. set: function (value) {
  46114. this._projectionTextureUpDirection = value;
  46115. this._projectionTextureProjectionLightDirty = true;
  46116. },
  46117. enumerable: true,
  46118. configurable: true
  46119. });
  46120. ;
  46121. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46122. /**
  46123. * Gets the projection texture of the light.
  46124. */
  46125. get: function () {
  46126. return this._projectionTexture;
  46127. },
  46128. /**
  46129. * Sets the projection texture of the light.
  46130. */
  46131. set: function (value) {
  46132. this._projectionTexture = value;
  46133. this._projectionTextureDirty = true;
  46134. },
  46135. enumerable: true,
  46136. configurable: true
  46137. });
  46138. /**
  46139. * Returns the string "SpotLight".
  46140. * @returns the class name
  46141. */
  46142. SpotLight.prototype.getClassName = function () {
  46143. return "SpotLight";
  46144. };
  46145. /**
  46146. * Returns the integer 2.
  46147. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46148. */
  46149. SpotLight.prototype.getTypeID = function () {
  46150. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46151. };
  46152. /**
  46153. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46154. */
  46155. SpotLight.prototype._setDirection = function (value) {
  46156. _super.prototype._setDirection.call(this, value);
  46157. this._projectionTextureViewLightDirty = true;
  46158. };
  46159. /**
  46160. * Overrides the position setter to recompute the projection texture view light Matrix.
  46161. */
  46162. SpotLight.prototype._setPosition = function (value) {
  46163. _super.prototype._setPosition.call(this, value);
  46164. this._projectionTextureViewLightDirty = true;
  46165. };
  46166. /**
  46167. * 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.
  46168. * Returns the SpotLight.
  46169. */
  46170. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46171. var activeCamera = this.getScene().activeCamera;
  46172. if (!activeCamera) {
  46173. return;
  46174. }
  46175. this._shadowAngleScale = this._shadowAngleScale || 1;
  46176. var angle = this._shadowAngleScale * this._angle;
  46177. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46178. };
  46179. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46180. this._projectionTextureViewLightDirty = false;
  46181. this._projectionTextureDirty = true;
  46182. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46183. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46184. };
  46185. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46186. this._projectionTextureProjectionLightDirty = false;
  46187. this._projectionTextureDirty = true;
  46188. var light_far = this.projectionTextureLightFar;
  46189. var light_near = this.projectionTextureLightNear;
  46190. var P = light_far / (light_far - light_near);
  46191. var Q = -P * light_near;
  46192. var S = 1.0 / Math.tan(this._angle / 2.0);
  46193. var A = 1.0;
  46194. 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);
  46195. };
  46196. /**
  46197. * Main function for light texture projection matrix computing.
  46198. */
  46199. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46200. this._projectionTextureDirty = false;
  46201. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46202. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46203. };
  46204. SpotLight.prototype._buildUniformLayout = function () {
  46205. this._uniformBuffer.addUniform("vLightData", 4);
  46206. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46207. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46208. this._uniformBuffer.addUniform("vLightDirection", 3);
  46209. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46210. this._uniformBuffer.addUniform("depthValues", 2);
  46211. this._uniformBuffer.create();
  46212. };
  46213. /**
  46214. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46215. * @param effect The effect to update
  46216. * @param lightIndex The index of the light in the effect to update
  46217. * @returns The spot light
  46218. */
  46219. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46220. var normalizeDirection;
  46221. if (this.computeTransformedInformation()) {
  46222. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46223. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46224. }
  46225. else {
  46226. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46227. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46228. }
  46229. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46230. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46231. if (this._projectionTextureViewLightDirty) {
  46232. this._computeProjectionTextureViewLightMatrix();
  46233. }
  46234. if (this._projectionTextureProjectionLightDirty) {
  46235. this._computeProjectionTextureProjectionLightMatrix();
  46236. }
  46237. if (this._projectionTextureDirty) {
  46238. this._computeProjectionTextureMatrix();
  46239. }
  46240. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46241. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46242. }
  46243. return this;
  46244. };
  46245. /**
  46246. * Disposes the light and the associated resources.
  46247. */
  46248. SpotLight.prototype.dispose = function () {
  46249. _super.prototype.dispose.call(this);
  46250. if (this._projectionTexture) {
  46251. this._projectionTexture.dispose();
  46252. }
  46253. };
  46254. __decorate([
  46255. BABYLON.serialize()
  46256. ], SpotLight.prototype, "angle", null);
  46257. __decorate([
  46258. BABYLON.serialize()
  46259. ], SpotLight.prototype, "shadowAngleScale", null);
  46260. __decorate([
  46261. BABYLON.serialize()
  46262. ], SpotLight.prototype, "exponent", void 0);
  46263. __decorate([
  46264. BABYLON.serialize()
  46265. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46266. __decorate([
  46267. BABYLON.serialize()
  46268. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46269. __decorate([
  46270. BABYLON.serialize()
  46271. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46272. __decorate([
  46273. BABYLON.serializeAsTexture("projectedLightTexture")
  46274. ], SpotLight.prototype, "_projectionTexture", void 0);
  46275. return SpotLight;
  46276. }(BABYLON.ShadowLight));
  46277. BABYLON.SpotLight = SpotLight;
  46278. })(BABYLON || (BABYLON = {}));
  46279. //# sourceMappingURL=babylon.spotLight.js.map
  46280. var BABYLON;
  46281. (function (BABYLON) {
  46282. /**
  46283. * Class used to override all child animations of a given target
  46284. */
  46285. var AnimationPropertiesOverride = /** @class */ (function () {
  46286. function AnimationPropertiesOverride() {
  46287. /**
  46288. * Gets or sets a value indicating if animation blending must be used
  46289. */
  46290. this.enableBlending = false;
  46291. /**
  46292. * Gets or sets the blending speed to use when enableBlending is true
  46293. */
  46294. this.blendingSpeed = 0.01;
  46295. /**
  46296. * Gets or sets the default loop mode to use
  46297. */
  46298. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46299. }
  46300. return AnimationPropertiesOverride;
  46301. }());
  46302. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46303. })(BABYLON || (BABYLON = {}));
  46304. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46305. var BABYLON;
  46306. (function (BABYLON) {
  46307. var AnimationRange = /** @class */ (function () {
  46308. function AnimationRange(name, from, to) {
  46309. this.name = name;
  46310. this.from = from;
  46311. this.to = to;
  46312. }
  46313. AnimationRange.prototype.clone = function () {
  46314. return new AnimationRange(this.name, this.from, this.to);
  46315. };
  46316. return AnimationRange;
  46317. }());
  46318. BABYLON.AnimationRange = AnimationRange;
  46319. /**
  46320. * Composed of a frame, and an action function
  46321. */
  46322. var AnimationEvent = /** @class */ (function () {
  46323. function AnimationEvent(frame, action, onlyOnce) {
  46324. this.frame = frame;
  46325. this.action = action;
  46326. this.onlyOnce = onlyOnce;
  46327. this.isDone = false;
  46328. }
  46329. return AnimationEvent;
  46330. }());
  46331. BABYLON.AnimationEvent = AnimationEvent;
  46332. var PathCursor = /** @class */ (function () {
  46333. function PathCursor(path) {
  46334. this.path = path;
  46335. this._onchange = new Array();
  46336. this.value = 0;
  46337. this.animations = new Array();
  46338. }
  46339. PathCursor.prototype.getPoint = function () {
  46340. var point = this.path.getPointAtLengthPosition(this.value);
  46341. return new BABYLON.Vector3(point.x, 0, point.y);
  46342. };
  46343. PathCursor.prototype.moveAhead = function (step) {
  46344. if (step === void 0) { step = 0.002; }
  46345. this.move(step);
  46346. return this;
  46347. };
  46348. PathCursor.prototype.moveBack = function (step) {
  46349. if (step === void 0) { step = 0.002; }
  46350. this.move(-step);
  46351. return this;
  46352. };
  46353. PathCursor.prototype.move = function (step) {
  46354. if (Math.abs(step) > 1) {
  46355. throw "step size should be less than 1.";
  46356. }
  46357. this.value += step;
  46358. this.ensureLimits();
  46359. this.raiseOnChange();
  46360. return this;
  46361. };
  46362. PathCursor.prototype.ensureLimits = function () {
  46363. while (this.value > 1) {
  46364. this.value -= 1;
  46365. }
  46366. while (this.value < 0) {
  46367. this.value += 1;
  46368. }
  46369. return this;
  46370. };
  46371. // used by animation engine
  46372. PathCursor.prototype.raiseOnChange = function () {
  46373. var _this = this;
  46374. this._onchange.forEach(function (f) { return f(_this); });
  46375. return this;
  46376. };
  46377. PathCursor.prototype.onchange = function (f) {
  46378. this._onchange.push(f);
  46379. return this;
  46380. };
  46381. return PathCursor;
  46382. }());
  46383. BABYLON.PathCursor = PathCursor;
  46384. var AnimationKeyInterpolation;
  46385. (function (AnimationKeyInterpolation) {
  46386. /**
  46387. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46388. */
  46389. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46390. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46391. var Animation = /** @class */ (function () {
  46392. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46393. this.name = name;
  46394. this.targetProperty = targetProperty;
  46395. this.framePerSecond = framePerSecond;
  46396. this.dataType = dataType;
  46397. this.loopMode = loopMode;
  46398. this.enableBlending = enableBlending;
  46399. this._runtimeAnimations = new Array();
  46400. // The set of event that will be linked to this animation
  46401. this._events = new Array();
  46402. this.blendingSpeed = 0.01;
  46403. this._ranges = {};
  46404. this.targetPropertyPath = targetProperty.split(".");
  46405. this.dataType = dataType;
  46406. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46407. }
  46408. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46409. var dataType = undefined;
  46410. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46411. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46412. }
  46413. else if (from instanceof BABYLON.Quaternion) {
  46414. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46415. }
  46416. else if (from instanceof BABYLON.Vector3) {
  46417. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46418. }
  46419. else if (from instanceof BABYLON.Vector2) {
  46420. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46421. }
  46422. else if (from instanceof BABYLON.Color3) {
  46423. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46424. }
  46425. else if (from instanceof BABYLON.Size) {
  46426. dataType = Animation.ANIMATIONTYPE_SIZE;
  46427. }
  46428. if (dataType == undefined) {
  46429. return null;
  46430. }
  46431. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46432. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46433. animation.setKeys(keys);
  46434. if (easingFunction !== undefined) {
  46435. animation.setEasingFunction(easingFunction);
  46436. }
  46437. return animation;
  46438. };
  46439. /**
  46440. * Sets up an animation.
  46441. * @param property the property to animate
  46442. * @param animationType the animation type to apply
  46443. * @param easingFunction the easing function used in the animation
  46444. * @returns The created animation
  46445. */
  46446. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46447. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46448. animation.setEasingFunction(easingFunction);
  46449. return animation;
  46450. };
  46451. /**
  46452. * Create and start an animation on a node
  46453. * @param {string} name defines the name of the global animation that will be run on all nodes
  46454. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46455. * @param {string} targetProperty defines property to animate
  46456. * @param {number} framePerSecond defines the number of frame per second yo use
  46457. * @param {number} totalFrame defines the number of frames in total
  46458. * @param {any} from defines the initial value
  46459. * @param {any} to defines the final value
  46460. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46461. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46462. * @param onAnimationEnd defines the callback to call when animation end
  46463. * @returns the animatable created for this animation
  46464. */
  46465. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46466. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46467. if (!animation) {
  46468. return null;
  46469. }
  46470. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46471. };
  46472. /**
  46473. * Create and start an animation on a node and its descendants
  46474. * @param {string} name defines the name of the global animation that will be run on all nodes
  46475. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46476. * @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.
  46477. * @param {string} targetProperty defines property to animate
  46478. * @param {number} framePerSecond defines the number of frame per second yo use
  46479. * @param {number} totalFrame defines the number of frames in total
  46480. * @param {any} from defines the initial value
  46481. * @param {any} to defines the final value
  46482. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46483. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46484. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46485. * @returns the list of animatables created for all nodes
  46486. * @example https://www.babylonjs-playground.com/#MH0VLI
  46487. */
  46488. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46489. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46490. if (!animation) {
  46491. return null;
  46492. }
  46493. var scene = node.getScene();
  46494. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46495. };
  46496. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46497. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46498. if (!animation) {
  46499. return null;
  46500. }
  46501. node.animations.push(animation);
  46502. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46503. };
  46504. /**
  46505. * Transition property of the Camera to the target Value.
  46506. * @param property The property to transition
  46507. * @param targetValue The target Value of the property
  46508. * @param host The object where the property to animate belongs
  46509. * @param scene Scene used to run the animation
  46510. * @param frameRate Framerate (in frame/s) to use
  46511. * @param transition The transition type we want to use
  46512. * @param duration The duration of the animation, in milliseconds
  46513. * @param onAnimationEnd Call back trigger at the end of the animation.
  46514. */
  46515. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46516. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46517. if (duration <= 0) {
  46518. host[property] = targetValue;
  46519. if (onAnimationEnd) {
  46520. onAnimationEnd();
  46521. }
  46522. return null;
  46523. }
  46524. var endFrame = frameRate * (duration / 1000);
  46525. transition.setKeys([{
  46526. frame: 0,
  46527. value: host[property].clone ? host[property].clone() : host[property]
  46528. },
  46529. {
  46530. frame: endFrame,
  46531. value: targetValue
  46532. }]);
  46533. if (!host.animations) {
  46534. host.animations = [];
  46535. }
  46536. host.animations.push(transition);
  46537. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46538. animation.onAnimationEnd = onAnimationEnd;
  46539. return animation;
  46540. };
  46541. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46542. /**
  46543. * Return the array of runtime animations currently using this animation
  46544. */
  46545. get: function () {
  46546. return this._runtimeAnimations;
  46547. },
  46548. enumerable: true,
  46549. configurable: true
  46550. });
  46551. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46552. get: function () {
  46553. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46554. var runtimeAnimation = _a[_i];
  46555. if (!runtimeAnimation.isStopped) {
  46556. return true;
  46557. }
  46558. }
  46559. return false;
  46560. },
  46561. enumerable: true,
  46562. configurable: true
  46563. });
  46564. // Methods
  46565. /**
  46566. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46567. */
  46568. Animation.prototype.toString = function (fullDetails) {
  46569. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46570. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46571. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46572. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46573. if (fullDetails) {
  46574. ret += ", Ranges: {";
  46575. var first = true;
  46576. for (var name in this._ranges) {
  46577. if (first) {
  46578. ret += ", ";
  46579. first = false;
  46580. }
  46581. ret += name;
  46582. }
  46583. ret += "}";
  46584. }
  46585. return ret;
  46586. };
  46587. /**
  46588. * Add an event to this animation.
  46589. */
  46590. Animation.prototype.addEvent = function (event) {
  46591. this._events.push(event);
  46592. };
  46593. /**
  46594. * Remove all events found at the given frame
  46595. * @param frame
  46596. */
  46597. Animation.prototype.removeEvents = function (frame) {
  46598. for (var index = 0; index < this._events.length; index++) {
  46599. if (this._events[index].frame === frame) {
  46600. this._events.splice(index, 1);
  46601. index--;
  46602. }
  46603. }
  46604. };
  46605. Animation.prototype.getEvents = function () {
  46606. return this._events;
  46607. };
  46608. Animation.prototype.createRange = function (name, from, to) {
  46609. // check name not already in use; could happen for bones after serialized
  46610. if (!this._ranges[name]) {
  46611. this._ranges[name] = new AnimationRange(name, from, to);
  46612. }
  46613. };
  46614. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46615. if (deleteFrames === void 0) { deleteFrames = true; }
  46616. var range = this._ranges[name];
  46617. if (!range) {
  46618. return;
  46619. }
  46620. if (deleteFrames) {
  46621. var from = range.from;
  46622. var to = range.to;
  46623. // this loop MUST go high to low for multiple splices to work
  46624. for (var key = this._keys.length - 1; key >= 0; key--) {
  46625. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46626. this._keys.splice(key, 1);
  46627. }
  46628. }
  46629. }
  46630. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46631. };
  46632. Animation.prototype.getRange = function (name) {
  46633. return this._ranges[name];
  46634. };
  46635. Animation.prototype.getKeys = function () {
  46636. return this._keys;
  46637. };
  46638. Animation.prototype.getHighestFrame = function () {
  46639. var ret = 0;
  46640. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46641. if (ret < this._keys[key].frame) {
  46642. ret = this._keys[key].frame;
  46643. }
  46644. }
  46645. return ret;
  46646. };
  46647. Animation.prototype.getEasingFunction = function () {
  46648. return this._easingFunction;
  46649. };
  46650. Animation.prototype.setEasingFunction = function (easingFunction) {
  46651. this._easingFunction = easingFunction;
  46652. };
  46653. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46654. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46655. };
  46656. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46657. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46658. };
  46659. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46660. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46661. };
  46662. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46663. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46664. };
  46665. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46666. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46667. };
  46668. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46669. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46670. };
  46671. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46672. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46673. };
  46674. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46675. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46676. };
  46677. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46678. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46679. };
  46680. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46681. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46682. };
  46683. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46684. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46685. };
  46686. Animation.prototype.clone = function () {
  46687. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46688. clone.enableBlending = this.enableBlending;
  46689. clone.blendingSpeed = this.blendingSpeed;
  46690. if (this._keys) {
  46691. clone.setKeys(this._keys);
  46692. }
  46693. if (this._ranges) {
  46694. clone._ranges = {};
  46695. for (var name in this._ranges) {
  46696. var range = this._ranges[name];
  46697. if (!range) {
  46698. continue;
  46699. }
  46700. clone._ranges[name] = range.clone();
  46701. }
  46702. }
  46703. return clone;
  46704. };
  46705. Animation.prototype.setKeys = function (values) {
  46706. this._keys = values.slice(0);
  46707. };
  46708. Animation.prototype.serialize = function () {
  46709. var serializationObject = {};
  46710. serializationObject.name = this.name;
  46711. serializationObject.property = this.targetProperty;
  46712. serializationObject.framePerSecond = this.framePerSecond;
  46713. serializationObject.dataType = this.dataType;
  46714. serializationObject.loopBehavior = this.loopMode;
  46715. serializationObject.enableBlending = this.enableBlending;
  46716. serializationObject.blendingSpeed = this.blendingSpeed;
  46717. var dataType = this.dataType;
  46718. serializationObject.keys = [];
  46719. var keys = this.getKeys();
  46720. for (var index = 0; index < keys.length; index++) {
  46721. var animationKey = keys[index];
  46722. var key = {};
  46723. key.frame = animationKey.frame;
  46724. switch (dataType) {
  46725. case Animation.ANIMATIONTYPE_FLOAT:
  46726. key.values = [animationKey.value];
  46727. break;
  46728. case Animation.ANIMATIONTYPE_QUATERNION:
  46729. case Animation.ANIMATIONTYPE_MATRIX:
  46730. case Animation.ANIMATIONTYPE_VECTOR3:
  46731. case Animation.ANIMATIONTYPE_COLOR3:
  46732. key.values = animationKey.value.asArray();
  46733. break;
  46734. }
  46735. serializationObject.keys.push(key);
  46736. }
  46737. serializationObject.ranges = [];
  46738. for (var name in this._ranges) {
  46739. var source = this._ranges[name];
  46740. if (!source) {
  46741. continue;
  46742. }
  46743. var range = {};
  46744. range.name = name;
  46745. range.from = source.from;
  46746. range.to = source.to;
  46747. serializationObject.ranges.push(range);
  46748. }
  46749. return serializationObject;
  46750. };
  46751. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46752. get: function () {
  46753. return Animation._ANIMATIONTYPE_FLOAT;
  46754. },
  46755. enumerable: true,
  46756. configurable: true
  46757. });
  46758. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46759. get: function () {
  46760. return Animation._ANIMATIONTYPE_VECTOR3;
  46761. },
  46762. enumerable: true,
  46763. configurable: true
  46764. });
  46765. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46766. get: function () {
  46767. return Animation._ANIMATIONTYPE_VECTOR2;
  46768. },
  46769. enumerable: true,
  46770. configurable: true
  46771. });
  46772. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46773. get: function () {
  46774. return Animation._ANIMATIONTYPE_SIZE;
  46775. },
  46776. enumerable: true,
  46777. configurable: true
  46778. });
  46779. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46780. get: function () {
  46781. return Animation._ANIMATIONTYPE_QUATERNION;
  46782. },
  46783. enumerable: true,
  46784. configurable: true
  46785. });
  46786. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46787. get: function () {
  46788. return Animation._ANIMATIONTYPE_MATRIX;
  46789. },
  46790. enumerable: true,
  46791. configurable: true
  46792. });
  46793. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46794. get: function () {
  46795. return Animation._ANIMATIONTYPE_COLOR3;
  46796. },
  46797. enumerable: true,
  46798. configurable: true
  46799. });
  46800. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46801. get: function () {
  46802. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46803. },
  46804. enumerable: true,
  46805. configurable: true
  46806. });
  46807. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46808. get: function () {
  46809. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46810. },
  46811. enumerable: true,
  46812. configurable: true
  46813. });
  46814. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46815. get: function () {
  46816. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46817. },
  46818. enumerable: true,
  46819. configurable: true
  46820. });
  46821. Animation.Parse = function (parsedAnimation) {
  46822. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46823. var dataType = parsedAnimation.dataType;
  46824. var keys = [];
  46825. var data;
  46826. var index;
  46827. if (parsedAnimation.enableBlending) {
  46828. animation.enableBlending = parsedAnimation.enableBlending;
  46829. }
  46830. if (parsedAnimation.blendingSpeed) {
  46831. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46832. }
  46833. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46834. var key = parsedAnimation.keys[index];
  46835. var inTangent;
  46836. var outTangent;
  46837. switch (dataType) {
  46838. case Animation.ANIMATIONTYPE_FLOAT:
  46839. data = key.values[0];
  46840. if (key.values.length >= 1) {
  46841. inTangent = key.values[1];
  46842. }
  46843. if (key.values.length >= 2) {
  46844. outTangent = key.values[2];
  46845. }
  46846. break;
  46847. case Animation.ANIMATIONTYPE_QUATERNION:
  46848. data = BABYLON.Quaternion.FromArray(key.values);
  46849. if (key.values.length >= 8) {
  46850. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46851. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46852. inTangent = _inTangent;
  46853. }
  46854. }
  46855. if (key.values.length >= 12) {
  46856. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46857. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46858. outTangent = _outTangent;
  46859. }
  46860. }
  46861. break;
  46862. case Animation.ANIMATIONTYPE_MATRIX:
  46863. data = BABYLON.Matrix.FromArray(key.values);
  46864. break;
  46865. case Animation.ANIMATIONTYPE_COLOR3:
  46866. data = BABYLON.Color3.FromArray(key.values);
  46867. break;
  46868. case Animation.ANIMATIONTYPE_VECTOR3:
  46869. default:
  46870. data = BABYLON.Vector3.FromArray(key.values);
  46871. break;
  46872. }
  46873. var keyData = {};
  46874. keyData.frame = key.frame;
  46875. keyData.value = data;
  46876. if (inTangent != undefined) {
  46877. keyData.inTangent = inTangent;
  46878. }
  46879. if (outTangent != undefined) {
  46880. keyData.outTangent = outTangent;
  46881. }
  46882. keys.push(keyData);
  46883. }
  46884. animation.setKeys(keys);
  46885. if (parsedAnimation.ranges) {
  46886. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46887. data = parsedAnimation.ranges[index];
  46888. animation.createRange(data.name, data.from, data.to);
  46889. }
  46890. }
  46891. return animation;
  46892. };
  46893. Animation.AppendSerializedAnimations = function (source, destination) {
  46894. if (source.animations) {
  46895. destination.animations = [];
  46896. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46897. var animation = source.animations[animationIndex];
  46898. destination.animations.push(animation.serialize());
  46899. }
  46900. }
  46901. };
  46902. Animation.AllowMatricesInterpolation = false;
  46903. // Statics
  46904. Animation._ANIMATIONTYPE_FLOAT = 0;
  46905. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46906. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46907. Animation._ANIMATIONTYPE_MATRIX = 3;
  46908. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46909. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46910. Animation._ANIMATIONTYPE_SIZE = 6;
  46911. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46912. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46913. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46914. return Animation;
  46915. }());
  46916. BABYLON.Animation = Animation;
  46917. })(BABYLON || (BABYLON = {}));
  46918. //# sourceMappingURL=babylon.animation.js.map
  46919. var BABYLON;
  46920. (function (BABYLON) {
  46921. /**
  46922. * This class defines the direct association between an animation and a target
  46923. */
  46924. var TargetedAnimation = /** @class */ (function () {
  46925. function TargetedAnimation() {
  46926. }
  46927. return TargetedAnimation;
  46928. }());
  46929. BABYLON.TargetedAnimation = TargetedAnimation;
  46930. /**
  46931. * Use this class to create coordinated animations on multiple targets
  46932. */
  46933. var AnimationGroup = /** @class */ (function () {
  46934. function AnimationGroup(name, scene) {
  46935. if (scene === void 0) { scene = null; }
  46936. this.name = name;
  46937. this._targetedAnimations = new Array();
  46938. this._animatables = new Array();
  46939. this._from = Number.MAX_VALUE;
  46940. this._to = -Number.MAX_VALUE;
  46941. this._speedRatio = 1;
  46942. this.onAnimationEndObservable = new BABYLON.Observable();
  46943. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46944. this._scene.animationGroups.push(this);
  46945. }
  46946. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46947. /**
  46948. * Define if the animations are started
  46949. */
  46950. get: function () {
  46951. return this._isStarted;
  46952. },
  46953. enumerable: true,
  46954. configurable: true
  46955. });
  46956. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46957. /**
  46958. * Gets or sets the speed ratio to use for all animations
  46959. */
  46960. get: function () {
  46961. return this._speedRatio;
  46962. },
  46963. /**
  46964. * Gets or sets the speed ratio to use for all animations
  46965. */
  46966. set: function (value) {
  46967. if (this._speedRatio === value) {
  46968. return;
  46969. }
  46970. this._speedRatio = value;
  46971. for (var index = 0; index < this._animatables.length; index++) {
  46972. var animatable = this._animatables[index];
  46973. animatable.speedRatio = this._speedRatio;
  46974. }
  46975. },
  46976. enumerable: true,
  46977. configurable: true
  46978. });
  46979. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46980. /**
  46981. * Gets the targeted animations for this animation group
  46982. */
  46983. get: function () {
  46984. return this._targetedAnimations;
  46985. },
  46986. enumerable: true,
  46987. configurable: true
  46988. });
  46989. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46990. /**
  46991. * returning the list of animatables controlled by this animation group.
  46992. */
  46993. get: function () {
  46994. return this._animatables;
  46995. },
  46996. enumerable: true,
  46997. configurable: true
  46998. });
  46999. /**
  47000. * Add an animation (with its target) in the group
  47001. * @param animation defines the animation we want to add
  47002. * @param target defines the target of the animation
  47003. * @returns the {BABYLON.TargetedAnimation} object
  47004. */
  47005. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47006. var targetedAnimation = {
  47007. animation: animation,
  47008. target: target
  47009. };
  47010. var keys = animation.getKeys();
  47011. if (this._from > keys[0].frame) {
  47012. this._from = keys[0].frame;
  47013. }
  47014. if (this._to < keys[keys.length - 1].frame) {
  47015. this._to = keys[keys.length - 1].frame;
  47016. }
  47017. this._targetedAnimations.push(targetedAnimation);
  47018. return targetedAnimation;
  47019. };
  47020. /**
  47021. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47022. * It can add constant keys at begin or end
  47023. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47024. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47025. */
  47026. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47027. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47028. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47029. beginFrame = Math.max(beginFrame, this._from);
  47030. endFrame = Math.min(endFrame, this._to);
  47031. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47032. var targetedAnimation = this._targetedAnimations[index];
  47033. var keys = targetedAnimation.animation.getKeys();
  47034. var startKey = keys[0];
  47035. var endKey = keys[keys.length - 1];
  47036. if (startKey.frame > beginFrame) {
  47037. var newKey = {
  47038. frame: beginFrame,
  47039. value: startKey.value,
  47040. inTangent: startKey.inTangent,
  47041. outTangent: startKey.outTangent,
  47042. interpolation: startKey.interpolation
  47043. };
  47044. keys.splice(0, 0, newKey);
  47045. }
  47046. if (endKey.frame < endFrame) {
  47047. var newKey = {
  47048. frame: endFrame,
  47049. value: endKey.value,
  47050. inTangent: endKey.outTangent,
  47051. outTangent: endKey.outTangent,
  47052. interpolation: endKey.interpolation
  47053. };
  47054. keys.push(newKey);
  47055. }
  47056. }
  47057. return this;
  47058. };
  47059. /**
  47060. * Start all animations on given targets
  47061. * @param loop defines if animations must loop
  47062. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47063. */
  47064. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47065. var _this = this;
  47066. if (loop === void 0) { loop = false; }
  47067. if (speedRatio === void 0) { speedRatio = 1; }
  47068. if (this._isStarted || this._targetedAnimations.length === 0) {
  47069. return this;
  47070. }
  47071. var _loop_1 = function () {
  47072. var targetedAnimation = this_1._targetedAnimations[index];
  47073. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47074. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47075. }));
  47076. };
  47077. var this_1 = this;
  47078. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47079. _loop_1();
  47080. }
  47081. this._speedRatio = speedRatio;
  47082. this._isStarted = true;
  47083. return this;
  47084. };
  47085. /**
  47086. * Pause all animations
  47087. */
  47088. AnimationGroup.prototype.pause = function () {
  47089. if (!this._isStarted) {
  47090. return this;
  47091. }
  47092. for (var index = 0; index < this._animatables.length; index++) {
  47093. var animatable = this._animatables[index];
  47094. animatable.pause();
  47095. }
  47096. return this;
  47097. };
  47098. /**
  47099. * Play all animations to initial state
  47100. * This function will start() the animations if they were not started or will restart() them if they were paused
  47101. * @param loop defines if animations must loop
  47102. */
  47103. AnimationGroup.prototype.play = function (loop) {
  47104. if (this.isStarted) {
  47105. if (loop !== undefined) {
  47106. for (var index = 0; index < this._animatables.length; index++) {
  47107. var animatable = this._animatables[index];
  47108. animatable.loopAnimation = loop;
  47109. }
  47110. }
  47111. this.restart();
  47112. }
  47113. else {
  47114. this.start(loop, this._speedRatio);
  47115. }
  47116. return this;
  47117. };
  47118. /**
  47119. * Reset all animations to initial state
  47120. */
  47121. AnimationGroup.prototype.reset = function () {
  47122. if (!this._isStarted) {
  47123. return this;
  47124. }
  47125. for (var index = 0; index < this._animatables.length; index++) {
  47126. var animatable = this._animatables[index];
  47127. animatable.reset();
  47128. }
  47129. return this;
  47130. };
  47131. /**
  47132. * Restart animations from key 0
  47133. */
  47134. AnimationGroup.prototype.restart = function () {
  47135. if (!this._isStarted) {
  47136. return this;
  47137. }
  47138. for (var index = 0; index < this._animatables.length; index++) {
  47139. var animatable = this._animatables[index];
  47140. animatable.restart();
  47141. }
  47142. return this;
  47143. };
  47144. /**
  47145. * Stop all animations
  47146. */
  47147. AnimationGroup.prototype.stop = function () {
  47148. if (!this._isStarted) {
  47149. return this;
  47150. }
  47151. for (var index = 0; index < this._animatables.length; index++) {
  47152. var animatable = this._animatables[index];
  47153. animatable.stop();
  47154. }
  47155. this._isStarted = false;
  47156. return this;
  47157. };
  47158. /**
  47159. * Goes to a specific frame in this animation group
  47160. *
  47161. * @param frame the frame number to go to
  47162. * @return the animationGroup
  47163. */
  47164. AnimationGroup.prototype.goToFrame = function (frame) {
  47165. if (!this._isStarted) {
  47166. return this;
  47167. }
  47168. for (var index = 0; index < this._animatables.length; index++) {
  47169. var animatable = this._animatables[index];
  47170. animatable.goToFrame(frame);
  47171. }
  47172. return this;
  47173. };
  47174. /**
  47175. * Dispose all associated resources
  47176. */
  47177. AnimationGroup.prototype.dispose = function () {
  47178. this._targetedAnimations = [];
  47179. this._animatables = [];
  47180. var index = this._scene.animationGroups.indexOf(this);
  47181. if (index > -1) {
  47182. this._scene.animationGroups.splice(index, 1);
  47183. }
  47184. };
  47185. return AnimationGroup;
  47186. }());
  47187. BABYLON.AnimationGroup = AnimationGroup;
  47188. })(BABYLON || (BABYLON = {}));
  47189. //# sourceMappingURL=babylon.animationGroup.js.map
  47190. var BABYLON;
  47191. (function (BABYLON) {
  47192. var RuntimeAnimation = /** @class */ (function () {
  47193. function RuntimeAnimation(target, animation) {
  47194. this._offsetsCache = {};
  47195. this._highLimitsCache = {};
  47196. this._stopped = false;
  47197. this._blendingFactor = 0;
  47198. this._ratioOffset = 0;
  47199. this._animation = animation;
  47200. this._target = target;
  47201. animation._runtimeAnimations.push(this);
  47202. }
  47203. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47204. get: function () {
  47205. return this._animation;
  47206. },
  47207. enumerable: true,
  47208. configurable: true
  47209. });
  47210. RuntimeAnimation.prototype.reset = function () {
  47211. this._offsetsCache = {};
  47212. this._highLimitsCache = {};
  47213. this.currentFrame = 0;
  47214. this._blendingFactor = 0;
  47215. this._originalBlendValue = null;
  47216. };
  47217. RuntimeAnimation.prototype.isStopped = function () {
  47218. return this._stopped;
  47219. };
  47220. RuntimeAnimation.prototype.dispose = function () {
  47221. var index = this._animation.runtimeAnimations.indexOf(this);
  47222. if (index > -1) {
  47223. this._animation.runtimeAnimations.splice(index, 1);
  47224. }
  47225. };
  47226. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47227. if (typeof value === "function") {
  47228. return value();
  47229. }
  47230. return value;
  47231. };
  47232. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47233. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47234. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47235. }
  47236. this.currentFrame = currentFrame;
  47237. var keys = this._animation.getKeys();
  47238. // Try to get a hash to find the right key
  47239. 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));
  47240. if (keys[startKeyIndex].frame >= currentFrame) {
  47241. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47242. startKeyIndex--;
  47243. }
  47244. }
  47245. for (var key = startKeyIndex; key < keys.length; key++) {
  47246. var endKey = keys[key + 1];
  47247. if (endKey.frame >= currentFrame) {
  47248. var startKey = keys[key];
  47249. var startValue = this._getKeyValue(startKey.value);
  47250. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47251. return startValue;
  47252. }
  47253. var endValue = this._getKeyValue(endKey.value);
  47254. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47255. var frameDelta = endKey.frame - startKey.frame;
  47256. // gradient : percent of currentFrame between the frame inf and the frame sup
  47257. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47258. // check for easingFunction and correction of gradient
  47259. var easingFunction = this._animation.getEasingFunction();
  47260. if (easingFunction != null) {
  47261. gradient = easingFunction.ease(gradient);
  47262. }
  47263. switch (this._animation.dataType) {
  47264. // Float
  47265. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47266. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47267. switch (loopMode) {
  47268. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47269. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47270. return floatValue;
  47271. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47272. return offsetValue * repeatCount + floatValue;
  47273. }
  47274. break;
  47275. // Quaternion
  47276. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47277. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47278. switch (loopMode) {
  47279. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47280. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47281. return quatValue;
  47282. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47283. return quatValue.add(offsetValue.scale(repeatCount));
  47284. }
  47285. return quatValue;
  47286. // Vector3
  47287. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47288. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47289. switch (loopMode) {
  47290. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47291. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47292. return vec3Value;
  47293. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47294. return vec3Value.add(offsetValue.scale(repeatCount));
  47295. }
  47296. // Vector2
  47297. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47298. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47299. switch (loopMode) {
  47300. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47301. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47302. return vec2Value;
  47303. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47304. return vec2Value.add(offsetValue.scale(repeatCount));
  47305. }
  47306. // Size
  47307. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47308. switch (loopMode) {
  47309. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47310. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47311. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47312. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47313. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47314. }
  47315. // Color3
  47316. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47317. switch (loopMode) {
  47318. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47319. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47320. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47321. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47322. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47323. }
  47324. // Matrix
  47325. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47326. switch (loopMode) {
  47327. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47328. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47329. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47330. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47331. }
  47332. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47333. return startValue;
  47334. }
  47335. default:
  47336. break;
  47337. }
  47338. break;
  47339. }
  47340. }
  47341. return this._getKeyValue(keys[keys.length - 1].value);
  47342. };
  47343. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47344. if (blend === void 0) { blend = false; }
  47345. // Set value
  47346. var path;
  47347. var destination;
  47348. var targetPropertyPath = this._animation.targetPropertyPath;
  47349. if (targetPropertyPath.length > 1) {
  47350. var property = this._target[targetPropertyPath[0]];
  47351. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47352. property = property[targetPropertyPath[index]];
  47353. }
  47354. path = targetPropertyPath[targetPropertyPath.length - 1];
  47355. destination = property;
  47356. }
  47357. else {
  47358. path = targetPropertyPath[0];
  47359. destination = this._target;
  47360. }
  47361. // Blending
  47362. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47363. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47364. if (enableBlending && this._blendingFactor <= 1.0) {
  47365. if (!this._originalBlendValue) {
  47366. if (destination[path].clone) {
  47367. this._originalBlendValue = destination[path].clone();
  47368. }
  47369. else {
  47370. this._originalBlendValue = destination[path];
  47371. }
  47372. }
  47373. if (this._originalBlendValue.prototype) {
  47374. if (this._originalBlendValue.prototype.Lerp) {
  47375. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47376. }
  47377. else {
  47378. destination[path] = currentValue;
  47379. }
  47380. }
  47381. else if (this._originalBlendValue.m) {
  47382. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47383. }
  47384. else {
  47385. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47386. }
  47387. this._blendingFactor += blendingSpeed;
  47388. }
  47389. else {
  47390. destination[path] = currentValue;
  47391. }
  47392. if (this._target.markAsDirty) {
  47393. this._target.markAsDirty(this._animation.targetProperty);
  47394. }
  47395. };
  47396. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47397. if (this._target && this._target.animationPropertiesOverride) {
  47398. return this._target.animationPropertiesOverride.loopMode;
  47399. }
  47400. return this._animation.loopMode;
  47401. };
  47402. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47403. var keys = this._animation.getKeys();
  47404. if (frame < keys[0].frame) {
  47405. frame = keys[0].frame;
  47406. }
  47407. else if (frame > keys[keys.length - 1].frame) {
  47408. frame = keys[keys.length - 1].frame;
  47409. }
  47410. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47411. this.setValue(currentValue);
  47412. };
  47413. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47414. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47415. this._ratioOffset = this._previousRatio - newRatio;
  47416. };
  47417. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47418. if (blend === void 0) { blend = false; }
  47419. var targetPropertyPath = this._animation.targetPropertyPath;
  47420. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47421. this._stopped = true;
  47422. return false;
  47423. }
  47424. var returnValue = true;
  47425. var keys = this._animation.getKeys();
  47426. // Adding a start key at frame 0 if missing
  47427. if (keys[0].frame !== 0) {
  47428. var newKey = { frame: 0, value: keys[0].value };
  47429. keys.splice(0, 0, newKey);
  47430. }
  47431. // Check limits
  47432. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47433. from = keys[0].frame;
  47434. }
  47435. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47436. to = keys[keys.length - 1].frame;
  47437. }
  47438. //to and from cannot be the same key
  47439. if (from === to) {
  47440. if (from > keys[0].frame) {
  47441. from--;
  47442. }
  47443. else if (to < keys[keys.length - 1].frame) {
  47444. to++;
  47445. }
  47446. }
  47447. // Compute ratio
  47448. var range = to - from;
  47449. var offsetValue;
  47450. // ratio represents the frame delta between from and to
  47451. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47452. var highLimitValue = 0;
  47453. this._previousDelay = delay;
  47454. this._previousRatio = ratio;
  47455. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47456. returnValue = false;
  47457. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47458. }
  47459. else {
  47460. // Get max value if required
  47461. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47462. var keyOffset = to.toString() + from.toString();
  47463. if (!this._offsetsCache[keyOffset]) {
  47464. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47465. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47466. switch (this._animation.dataType) {
  47467. // Float
  47468. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47469. this._offsetsCache[keyOffset] = toValue - fromValue;
  47470. break;
  47471. // Quaternion
  47472. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47473. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47474. break;
  47475. // Vector3
  47476. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47477. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47478. // Vector2
  47479. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47480. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47481. // Size
  47482. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47483. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47484. // Color3
  47485. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47486. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47487. default:
  47488. break;
  47489. }
  47490. this._highLimitsCache[keyOffset] = toValue;
  47491. }
  47492. highLimitValue = this._highLimitsCache[keyOffset];
  47493. offsetValue = this._offsetsCache[keyOffset];
  47494. }
  47495. }
  47496. if (offsetValue === undefined) {
  47497. switch (this._animation.dataType) {
  47498. // Float
  47499. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47500. offsetValue = 0;
  47501. break;
  47502. // Quaternion
  47503. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47504. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47505. break;
  47506. // Vector3
  47507. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47508. offsetValue = BABYLON.Vector3.Zero();
  47509. break;
  47510. // Vector2
  47511. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47512. offsetValue = BABYLON.Vector2.Zero();
  47513. break;
  47514. // Size
  47515. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47516. offsetValue = BABYLON.Size.Zero();
  47517. break;
  47518. // Color3
  47519. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47520. offsetValue = BABYLON.Color3.Black();
  47521. }
  47522. }
  47523. // Compute value
  47524. var repeatCount = (ratio / range) >> 0;
  47525. var currentFrame = returnValue ? from + ratio % range : to;
  47526. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47527. // Set value
  47528. this.setValue(currentValue);
  47529. // Check events
  47530. var events = this._animation.getEvents();
  47531. for (var index = 0; index < events.length; index++) {
  47532. // Make sure current frame has passed event frame and that event frame is within the current range
  47533. // Also, handle both forward and reverse animations
  47534. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47535. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47536. var event = events[index];
  47537. if (!event.isDone) {
  47538. // If event should be done only once, remove it.
  47539. if (event.onlyOnce) {
  47540. events.splice(index, 1);
  47541. index--;
  47542. }
  47543. event.isDone = true;
  47544. event.action();
  47545. } // Don't do anything if the event has already be done.
  47546. }
  47547. else if (events[index].isDone && !events[index].onlyOnce) {
  47548. // reset event, the animation is looping
  47549. events[index].isDone = false;
  47550. }
  47551. }
  47552. if (!returnValue) {
  47553. this._stopped = true;
  47554. }
  47555. return returnValue;
  47556. };
  47557. return RuntimeAnimation;
  47558. }());
  47559. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47560. })(BABYLON || (BABYLON = {}));
  47561. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47562. var BABYLON;
  47563. (function (BABYLON) {
  47564. var Animatable = /** @class */ (function () {
  47565. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47566. if (fromFrame === void 0) { fromFrame = 0; }
  47567. if (toFrame === void 0) { toFrame = 100; }
  47568. if (loopAnimation === void 0) { loopAnimation = false; }
  47569. if (speedRatio === void 0) { speedRatio = 1.0; }
  47570. this.target = target;
  47571. this.fromFrame = fromFrame;
  47572. this.toFrame = toFrame;
  47573. this.loopAnimation = loopAnimation;
  47574. this.onAnimationEnd = onAnimationEnd;
  47575. this._localDelayOffset = null;
  47576. this._pausedDelay = null;
  47577. this._runtimeAnimations = new Array();
  47578. this._paused = false;
  47579. this._speedRatio = 1;
  47580. this.animationStarted = false;
  47581. if (animations) {
  47582. this.appendAnimations(target, animations);
  47583. }
  47584. this._speedRatio = speedRatio;
  47585. this._scene = scene;
  47586. scene._activeAnimatables.push(this);
  47587. }
  47588. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47589. get: function () {
  47590. return this._speedRatio;
  47591. },
  47592. set: function (value) {
  47593. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47594. var animation = this._runtimeAnimations[index];
  47595. animation._prepareForSpeedRatioChange(value);
  47596. }
  47597. this._speedRatio = value;
  47598. },
  47599. enumerable: true,
  47600. configurable: true
  47601. });
  47602. // Methods
  47603. Animatable.prototype.getAnimations = function () {
  47604. return this._runtimeAnimations;
  47605. };
  47606. Animatable.prototype.appendAnimations = function (target, animations) {
  47607. for (var index = 0; index < animations.length; index++) {
  47608. var animation = animations[index];
  47609. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47610. }
  47611. };
  47612. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47613. var runtimeAnimations = this._runtimeAnimations;
  47614. for (var index = 0; index < runtimeAnimations.length; index++) {
  47615. if (runtimeAnimations[index].animation.targetProperty === property) {
  47616. return runtimeAnimations[index].animation;
  47617. }
  47618. }
  47619. return null;
  47620. };
  47621. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47622. var runtimeAnimations = this._runtimeAnimations;
  47623. for (var index = 0; index < runtimeAnimations.length; index++) {
  47624. if (runtimeAnimations[index].animation.targetProperty === property) {
  47625. return runtimeAnimations[index];
  47626. }
  47627. }
  47628. return null;
  47629. };
  47630. Animatable.prototype.reset = function () {
  47631. var runtimeAnimations = this._runtimeAnimations;
  47632. for (var index = 0; index < runtimeAnimations.length; index++) {
  47633. runtimeAnimations[index].reset();
  47634. }
  47635. // Reset to original value
  47636. for (index = 0; index < runtimeAnimations.length; index++) {
  47637. var animation = runtimeAnimations[index];
  47638. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47639. }
  47640. this._localDelayOffset = null;
  47641. this._pausedDelay = null;
  47642. };
  47643. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47644. var runtimeAnimations = this._runtimeAnimations;
  47645. for (var index = 0; index < runtimeAnimations.length; index++) {
  47646. runtimeAnimations[index].animation.enableBlending = true;
  47647. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47648. }
  47649. };
  47650. Animatable.prototype.disableBlending = function () {
  47651. var runtimeAnimations = this._runtimeAnimations;
  47652. for (var index = 0; index < runtimeAnimations.length; index++) {
  47653. runtimeAnimations[index].animation.enableBlending = false;
  47654. }
  47655. };
  47656. Animatable.prototype.goToFrame = function (frame) {
  47657. var runtimeAnimations = this._runtimeAnimations;
  47658. if (runtimeAnimations[0]) {
  47659. var fps = runtimeAnimations[0].animation.framePerSecond;
  47660. var currentFrame = runtimeAnimations[0].currentFrame;
  47661. var adjustTime = frame - currentFrame;
  47662. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47663. if (this._localDelayOffset === null) {
  47664. this._localDelayOffset = 0;
  47665. }
  47666. this._localDelayOffset -= delay;
  47667. }
  47668. for (var index = 0; index < runtimeAnimations.length; index++) {
  47669. runtimeAnimations[index].goToFrame(frame);
  47670. }
  47671. };
  47672. Animatable.prototype.pause = function () {
  47673. if (this._paused) {
  47674. return;
  47675. }
  47676. this._paused = true;
  47677. };
  47678. Animatable.prototype.restart = function () {
  47679. this._paused = false;
  47680. };
  47681. Animatable.prototype.stop = function (animationName) {
  47682. if (animationName) {
  47683. var idx = this._scene._activeAnimatables.indexOf(this);
  47684. if (idx > -1) {
  47685. var runtimeAnimations = this._runtimeAnimations;
  47686. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47687. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47688. continue;
  47689. }
  47690. runtimeAnimations[index].dispose();
  47691. runtimeAnimations.splice(index, 1);
  47692. }
  47693. if (runtimeAnimations.length == 0) {
  47694. this._scene._activeAnimatables.splice(idx, 1);
  47695. if (this.onAnimationEnd) {
  47696. this.onAnimationEnd();
  47697. }
  47698. }
  47699. }
  47700. }
  47701. else {
  47702. var index = this._scene._activeAnimatables.indexOf(this);
  47703. if (index > -1) {
  47704. this._scene._activeAnimatables.splice(index, 1);
  47705. var runtimeAnimations = this._runtimeAnimations;
  47706. for (var index = 0; index < runtimeAnimations.length; index++) {
  47707. runtimeAnimations[index].dispose();
  47708. }
  47709. if (this.onAnimationEnd) {
  47710. this.onAnimationEnd();
  47711. }
  47712. }
  47713. }
  47714. };
  47715. Animatable.prototype._animate = function (delay) {
  47716. if (this._paused) {
  47717. this.animationStarted = false;
  47718. if (this._pausedDelay === null) {
  47719. this._pausedDelay = delay;
  47720. }
  47721. return true;
  47722. }
  47723. if (this._localDelayOffset === null) {
  47724. this._localDelayOffset = delay;
  47725. this._pausedDelay = null;
  47726. }
  47727. else if (this._pausedDelay !== null) {
  47728. this._localDelayOffset += delay - this._pausedDelay;
  47729. this._pausedDelay = null;
  47730. }
  47731. // Animating
  47732. var running = false;
  47733. var runtimeAnimations = this._runtimeAnimations;
  47734. var index;
  47735. for (index = 0; index < runtimeAnimations.length; index++) {
  47736. var animation = runtimeAnimations[index];
  47737. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47738. running = running || isRunning;
  47739. }
  47740. this.animationStarted = running;
  47741. if (!running) {
  47742. // Remove from active animatables
  47743. index = this._scene._activeAnimatables.indexOf(this);
  47744. this._scene._activeAnimatables.splice(index, 1);
  47745. // Dispose all runtime animations
  47746. for (index = 0; index < runtimeAnimations.length; index++) {
  47747. runtimeAnimations[index].dispose();
  47748. }
  47749. }
  47750. if (!running && this.onAnimationEnd) {
  47751. this.onAnimationEnd();
  47752. this.onAnimationEnd = null;
  47753. }
  47754. return running;
  47755. };
  47756. return Animatable;
  47757. }());
  47758. BABYLON.Animatable = Animatable;
  47759. })(BABYLON || (BABYLON = {}));
  47760. //# sourceMappingURL=babylon.animatable.js.map
  47761. var BABYLON;
  47762. (function (BABYLON) {
  47763. var EasingFunction = /** @class */ (function () {
  47764. function EasingFunction() {
  47765. // Properties
  47766. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47767. }
  47768. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47769. get: function () {
  47770. return EasingFunction._EASINGMODE_EASEIN;
  47771. },
  47772. enumerable: true,
  47773. configurable: true
  47774. });
  47775. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47776. get: function () {
  47777. return EasingFunction._EASINGMODE_EASEOUT;
  47778. },
  47779. enumerable: true,
  47780. configurable: true
  47781. });
  47782. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47783. get: function () {
  47784. return EasingFunction._EASINGMODE_EASEINOUT;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47790. var n = Math.min(Math.max(easingMode, 0), 2);
  47791. this._easingMode = n;
  47792. };
  47793. EasingFunction.prototype.getEasingMode = function () {
  47794. return this._easingMode;
  47795. };
  47796. EasingFunction.prototype.easeInCore = function (gradient) {
  47797. throw new Error('You must implement this method');
  47798. };
  47799. EasingFunction.prototype.ease = function (gradient) {
  47800. switch (this._easingMode) {
  47801. case EasingFunction.EASINGMODE_EASEIN:
  47802. return this.easeInCore(gradient);
  47803. case EasingFunction.EASINGMODE_EASEOUT:
  47804. return (1 - this.easeInCore(1 - gradient));
  47805. }
  47806. if (gradient >= 0.5) {
  47807. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47808. }
  47809. return (this.easeInCore(gradient * 2) * 0.5);
  47810. };
  47811. //Statics
  47812. EasingFunction._EASINGMODE_EASEIN = 0;
  47813. EasingFunction._EASINGMODE_EASEOUT = 1;
  47814. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47815. return EasingFunction;
  47816. }());
  47817. BABYLON.EasingFunction = EasingFunction;
  47818. var CircleEase = /** @class */ (function (_super) {
  47819. __extends(CircleEase, _super);
  47820. function CircleEase() {
  47821. return _super !== null && _super.apply(this, arguments) || this;
  47822. }
  47823. CircleEase.prototype.easeInCore = function (gradient) {
  47824. gradient = Math.max(0, Math.min(1, gradient));
  47825. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47826. };
  47827. return CircleEase;
  47828. }(EasingFunction));
  47829. BABYLON.CircleEase = CircleEase;
  47830. var BackEase = /** @class */ (function (_super) {
  47831. __extends(BackEase, _super);
  47832. function BackEase(amplitude) {
  47833. if (amplitude === void 0) { amplitude = 1; }
  47834. var _this = _super.call(this) || this;
  47835. _this.amplitude = amplitude;
  47836. return _this;
  47837. }
  47838. BackEase.prototype.easeInCore = function (gradient) {
  47839. var num = Math.max(0, this.amplitude);
  47840. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47841. };
  47842. return BackEase;
  47843. }(EasingFunction));
  47844. BABYLON.BackEase = BackEase;
  47845. var BounceEase = /** @class */ (function (_super) {
  47846. __extends(BounceEase, _super);
  47847. function BounceEase(bounces, bounciness) {
  47848. if (bounces === void 0) { bounces = 3; }
  47849. if (bounciness === void 0) { bounciness = 2; }
  47850. var _this = _super.call(this) || this;
  47851. _this.bounces = bounces;
  47852. _this.bounciness = bounciness;
  47853. return _this;
  47854. }
  47855. BounceEase.prototype.easeInCore = function (gradient) {
  47856. var y = Math.max(0.0, this.bounces);
  47857. var bounciness = this.bounciness;
  47858. if (bounciness <= 1.0) {
  47859. bounciness = 1.001;
  47860. }
  47861. var num9 = Math.pow(bounciness, y);
  47862. var num5 = 1.0 - bounciness;
  47863. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47864. var num15 = gradient * num4;
  47865. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47866. var num3 = Math.floor(num65);
  47867. var num13 = num3 + 1.0;
  47868. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47869. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47870. var num7 = (num8 + num12) * 0.5;
  47871. var num6 = gradient - num7;
  47872. var num2 = num7 - num8;
  47873. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47874. };
  47875. return BounceEase;
  47876. }(EasingFunction));
  47877. BABYLON.BounceEase = BounceEase;
  47878. var CubicEase = /** @class */ (function (_super) {
  47879. __extends(CubicEase, _super);
  47880. function CubicEase() {
  47881. return _super !== null && _super.apply(this, arguments) || this;
  47882. }
  47883. CubicEase.prototype.easeInCore = function (gradient) {
  47884. return (gradient * gradient * gradient);
  47885. };
  47886. return CubicEase;
  47887. }(EasingFunction));
  47888. BABYLON.CubicEase = CubicEase;
  47889. var ElasticEase = /** @class */ (function (_super) {
  47890. __extends(ElasticEase, _super);
  47891. function ElasticEase(oscillations, springiness) {
  47892. if (oscillations === void 0) { oscillations = 3; }
  47893. if (springiness === void 0) { springiness = 3; }
  47894. var _this = _super.call(this) || this;
  47895. _this.oscillations = oscillations;
  47896. _this.springiness = springiness;
  47897. return _this;
  47898. }
  47899. ElasticEase.prototype.easeInCore = function (gradient) {
  47900. var num2;
  47901. var num3 = Math.max(0.0, this.oscillations);
  47902. var num = Math.max(0.0, this.springiness);
  47903. if (num == 0) {
  47904. num2 = gradient;
  47905. }
  47906. else {
  47907. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47908. }
  47909. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47910. };
  47911. return ElasticEase;
  47912. }(EasingFunction));
  47913. BABYLON.ElasticEase = ElasticEase;
  47914. var ExponentialEase = /** @class */ (function (_super) {
  47915. __extends(ExponentialEase, _super);
  47916. function ExponentialEase(exponent) {
  47917. if (exponent === void 0) { exponent = 2; }
  47918. var _this = _super.call(this) || this;
  47919. _this.exponent = exponent;
  47920. return _this;
  47921. }
  47922. ExponentialEase.prototype.easeInCore = function (gradient) {
  47923. if (this.exponent <= 0) {
  47924. return gradient;
  47925. }
  47926. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47927. };
  47928. return ExponentialEase;
  47929. }(EasingFunction));
  47930. BABYLON.ExponentialEase = ExponentialEase;
  47931. var PowerEase = /** @class */ (function (_super) {
  47932. __extends(PowerEase, _super);
  47933. function PowerEase(power) {
  47934. if (power === void 0) { power = 2; }
  47935. var _this = _super.call(this) || this;
  47936. _this.power = power;
  47937. return _this;
  47938. }
  47939. PowerEase.prototype.easeInCore = function (gradient) {
  47940. var y = Math.max(0.0, this.power);
  47941. return Math.pow(gradient, y);
  47942. };
  47943. return PowerEase;
  47944. }(EasingFunction));
  47945. BABYLON.PowerEase = PowerEase;
  47946. var QuadraticEase = /** @class */ (function (_super) {
  47947. __extends(QuadraticEase, _super);
  47948. function QuadraticEase() {
  47949. return _super !== null && _super.apply(this, arguments) || this;
  47950. }
  47951. QuadraticEase.prototype.easeInCore = function (gradient) {
  47952. return (gradient * gradient);
  47953. };
  47954. return QuadraticEase;
  47955. }(EasingFunction));
  47956. BABYLON.QuadraticEase = QuadraticEase;
  47957. var QuarticEase = /** @class */ (function (_super) {
  47958. __extends(QuarticEase, _super);
  47959. function QuarticEase() {
  47960. return _super !== null && _super.apply(this, arguments) || this;
  47961. }
  47962. QuarticEase.prototype.easeInCore = function (gradient) {
  47963. return (gradient * gradient * gradient * gradient);
  47964. };
  47965. return QuarticEase;
  47966. }(EasingFunction));
  47967. BABYLON.QuarticEase = QuarticEase;
  47968. var QuinticEase = /** @class */ (function (_super) {
  47969. __extends(QuinticEase, _super);
  47970. function QuinticEase() {
  47971. return _super !== null && _super.apply(this, arguments) || this;
  47972. }
  47973. QuinticEase.prototype.easeInCore = function (gradient) {
  47974. return (gradient * gradient * gradient * gradient * gradient);
  47975. };
  47976. return QuinticEase;
  47977. }(EasingFunction));
  47978. BABYLON.QuinticEase = QuinticEase;
  47979. var SineEase = /** @class */ (function (_super) {
  47980. __extends(SineEase, _super);
  47981. function SineEase() {
  47982. return _super !== null && _super.apply(this, arguments) || this;
  47983. }
  47984. SineEase.prototype.easeInCore = function (gradient) {
  47985. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47986. };
  47987. return SineEase;
  47988. }(EasingFunction));
  47989. BABYLON.SineEase = SineEase;
  47990. var BezierCurveEase = /** @class */ (function (_super) {
  47991. __extends(BezierCurveEase, _super);
  47992. function BezierCurveEase(x1, y1, x2, y2) {
  47993. if (x1 === void 0) { x1 = 0; }
  47994. if (y1 === void 0) { y1 = 0; }
  47995. if (x2 === void 0) { x2 = 1; }
  47996. if (y2 === void 0) { y2 = 1; }
  47997. var _this = _super.call(this) || this;
  47998. _this.x1 = x1;
  47999. _this.y1 = y1;
  48000. _this.x2 = x2;
  48001. _this.y2 = y2;
  48002. return _this;
  48003. }
  48004. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48005. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48006. };
  48007. return BezierCurveEase;
  48008. }(EasingFunction));
  48009. BABYLON.BezierCurveEase = BezierCurveEase;
  48010. })(BABYLON || (BABYLON = {}));
  48011. //# sourceMappingURL=babylon.easing.js.map
  48012. var BABYLON;
  48013. (function (BABYLON) {
  48014. var Condition = /** @class */ (function () {
  48015. function Condition(actionManager) {
  48016. this._actionManager = actionManager;
  48017. }
  48018. Condition.prototype.isValid = function () {
  48019. return true;
  48020. };
  48021. Condition.prototype._getProperty = function (propertyPath) {
  48022. return this._actionManager._getProperty(propertyPath);
  48023. };
  48024. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48025. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48026. };
  48027. Condition.prototype.serialize = function () {
  48028. };
  48029. Condition.prototype._serialize = function (serializedCondition) {
  48030. return {
  48031. type: 2,
  48032. children: [],
  48033. name: serializedCondition.name,
  48034. properties: serializedCondition.properties
  48035. };
  48036. };
  48037. return Condition;
  48038. }());
  48039. BABYLON.Condition = Condition;
  48040. var ValueCondition = /** @class */ (function (_super) {
  48041. __extends(ValueCondition, _super);
  48042. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48043. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48044. var _this = _super.call(this, actionManager) || this;
  48045. _this.propertyPath = propertyPath;
  48046. _this.value = value;
  48047. _this.operator = operator;
  48048. _this._target = target;
  48049. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48050. _this._property = _this._getProperty(_this.propertyPath);
  48051. return _this;
  48052. }
  48053. Object.defineProperty(ValueCondition, "IsEqual", {
  48054. get: function () {
  48055. return ValueCondition._IsEqual;
  48056. },
  48057. enumerable: true,
  48058. configurable: true
  48059. });
  48060. Object.defineProperty(ValueCondition, "IsDifferent", {
  48061. get: function () {
  48062. return ValueCondition._IsDifferent;
  48063. },
  48064. enumerable: true,
  48065. configurable: true
  48066. });
  48067. Object.defineProperty(ValueCondition, "IsGreater", {
  48068. get: function () {
  48069. return ValueCondition._IsGreater;
  48070. },
  48071. enumerable: true,
  48072. configurable: true
  48073. });
  48074. Object.defineProperty(ValueCondition, "IsLesser", {
  48075. get: function () {
  48076. return ValueCondition._IsLesser;
  48077. },
  48078. enumerable: true,
  48079. configurable: true
  48080. });
  48081. // Methods
  48082. ValueCondition.prototype.isValid = function () {
  48083. switch (this.operator) {
  48084. case ValueCondition.IsGreater:
  48085. return this._effectiveTarget[this._property] > this.value;
  48086. case ValueCondition.IsLesser:
  48087. return this._effectiveTarget[this._property] < this.value;
  48088. case ValueCondition.IsEqual:
  48089. case ValueCondition.IsDifferent:
  48090. var check;
  48091. if (this.value.equals) {
  48092. check = this.value.equals(this._effectiveTarget[this._property]);
  48093. }
  48094. else {
  48095. check = this.value === this._effectiveTarget[this._property];
  48096. }
  48097. return this.operator === ValueCondition.IsEqual ? check : !check;
  48098. }
  48099. return false;
  48100. };
  48101. ValueCondition.prototype.serialize = function () {
  48102. return this._serialize({
  48103. name: "ValueCondition",
  48104. properties: [
  48105. BABYLON.Action._GetTargetProperty(this._target),
  48106. { name: "propertyPath", value: this.propertyPath },
  48107. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48108. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48109. ]
  48110. });
  48111. };
  48112. ValueCondition.GetOperatorName = function (operator) {
  48113. switch (operator) {
  48114. case ValueCondition._IsEqual: return "IsEqual";
  48115. case ValueCondition._IsDifferent: return "IsDifferent";
  48116. case ValueCondition._IsGreater: return "IsGreater";
  48117. case ValueCondition._IsLesser: return "IsLesser";
  48118. default: return "";
  48119. }
  48120. };
  48121. // Statics
  48122. ValueCondition._IsEqual = 0;
  48123. ValueCondition._IsDifferent = 1;
  48124. ValueCondition._IsGreater = 2;
  48125. ValueCondition._IsLesser = 3;
  48126. return ValueCondition;
  48127. }(Condition));
  48128. BABYLON.ValueCondition = ValueCondition;
  48129. var PredicateCondition = /** @class */ (function (_super) {
  48130. __extends(PredicateCondition, _super);
  48131. function PredicateCondition(actionManager, predicate) {
  48132. var _this = _super.call(this, actionManager) || this;
  48133. _this.predicate = predicate;
  48134. return _this;
  48135. }
  48136. PredicateCondition.prototype.isValid = function () {
  48137. return this.predicate();
  48138. };
  48139. return PredicateCondition;
  48140. }(Condition));
  48141. BABYLON.PredicateCondition = PredicateCondition;
  48142. var StateCondition = /** @class */ (function (_super) {
  48143. __extends(StateCondition, _super);
  48144. function StateCondition(actionManager, target, value) {
  48145. var _this = _super.call(this, actionManager) || this;
  48146. _this.value = value;
  48147. _this._target = target;
  48148. return _this;
  48149. }
  48150. // Methods
  48151. StateCondition.prototype.isValid = function () {
  48152. return this._target.state === this.value;
  48153. };
  48154. StateCondition.prototype.serialize = function () {
  48155. return this._serialize({
  48156. name: "StateCondition",
  48157. properties: [
  48158. BABYLON.Action._GetTargetProperty(this._target),
  48159. { name: "value", value: this.value }
  48160. ]
  48161. });
  48162. };
  48163. return StateCondition;
  48164. }(Condition));
  48165. BABYLON.StateCondition = StateCondition;
  48166. })(BABYLON || (BABYLON = {}));
  48167. //# sourceMappingURL=babylon.condition.js.map
  48168. var BABYLON;
  48169. (function (BABYLON) {
  48170. var Action = /** @class */ (function () {
  48171. function Action(triggerOptions, condition) {
  48172. this.triggerOptions = triggerOptions;
  48173. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48174. if (triggerOptions.parameter) {
  48175. this.trigger = triggerOptions.trigger;
  48176. this._triggerParameter = triggerOptions.parameter;
  48177. }
  48178. else {
  48179. this.trigger = triggerOptions;
  48180. }
  48181. this._nextActiveAction = this;
  48182. this._condition = condition;
  48183. }
  48184. // Methods
  48185. Action.prototype._prepare = function () {
  48186. };
  48187. Action.prototype.getTriggerParameter = function () {
  48188. return this._triggerParameter;
  48189. };
  48190. Action.prototype._executeCurrent = function (evt) {
  48191. if (this._nextActiveAction._condition) {
  48192. var condition = this._nextActiveAction._condition;
  48193. var currentRenderId = this._actionManager.getScene().getRenderId();
  48194. // We cache the current evaluation for the current frame
  48195. if (condition._evaluationId === currentRenderId) {
  48196. if (!condition._currentResult) {
  48197. return;
  48198. }
  48199. }
  48200. else {
  48201. condition._evaluationId = currentRenderId;
  48202. if (!condition.isValid()) {
  48203. condition._currentResult = false;
  48204. return;
  48205. }
  48206. condition._currentResult = true;
  48207. }
  48208. }
  48209. this.onBeforeExecuteObservable.notifyObservers(this);
  48210. this._nextActiveAction.execute(evt);
  48211. this.skipToNextActiveAction();
  48212. };
  48213. Action.prototype.execute = function (evt) {
  48214. };
  48215. Action.prototype.skipToNextActiveAction = function () {
  48216. if (this._nextActiveAction._child) {
  48217. if (!this._nextActiveAction._child._actionManager) {
  48218. this._nextActiveAction._child._actionManager = this._actionManager;
  48219. }
  48220. this._nextActiveAction = this._nextActiveAction._child;
  48221. }
  48222. else {
  48223. this._nextActiveAction = this;
  48224. }
  48225. };
  48226. Action.prototype.then = function (action) {
  48227. this._child = action;
  48228. action._actionManager = this._actionManager;
  48229. action._prepare();
  48230. return action;
  48231. };
  48232. Action.prototype._getProperty = function (propertyPath) {
  48233. return this._actionManager._getProperty(propertyPath);
  48234. };
  48235. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48236. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48237. };
  48238. Action.prototype.serialize = function (parent) {
  48239. };
  48240. // Called by BABYLON.Action objects in serialize(...). Internal use
  48241. Action.prototype._serialize = function (serializedAction, parent) {
  48242. var serializationObject = {
  48243. type: 1,
  48244. children: [],
  48245. name: serializedAction.name,
  48246. properties: serializedAction.properties || []
  48247. };
  48248. // Serialize child
  48249. if (this._child) {
  48250. this._child.serialize(serializationObject);
  48251. }
  48252. // Check if "this" has a condition
  48253. if (this._condition) {
  48254. var serializedCondition = this._condition.serialize();
  48255. serializedCondition.children.push(serializationObject);
  48256. if (parent) {
  48257. parent.children.push(serializedCondition);
  48258. }
  48259. return serializedCondition;
  48260. }
  48261. if (parent) {
  48262. parent.children.push(serializationObject);
  48263. }
  48264. return serializationObject;
  48265. };
  48266. Action._SerializeValueAsString = function (value) {
  48267. if (typeof value === "number") {
  48268. return value.toString();
  48269. }
  48270. if (typeof value === "boolean") {
  48271. return value ? "true" : "false";
  48272. }
  48273. if (value instanceof BABYLON.Vector2) {
  48274. return value.x + ", " + value.y;
  48275. }
  48276. if (value instanceof BABYLON.Vector3) {
  48277. return value.x + ", " + value.y + ", " + value.z;
  48278. }
  48279. if (value instanceof BABYLON.Color3) {
  48280. return value.r + ", " + value.g + ", " + value.b;
  48281. }
  48282. if (value instanceof BABYLON.Color4) {
  48283. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48284. }
  48285. return value; // string
  48286. };
  48287. Action._GetTargetProperty = function (target) {
  48288. return {
  48289. name: "target",
  48290. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48291. : target instanceof BABYLON.Light ? "LightProperties"
  48292. : target instanceof BABYLON.Camera ? "CameraProperties"
  48293. : "SceneProperties",
  48294. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48295. };
  48296. };
  48297. return Action;
  48298. }());
  48299. BABYLON.Action = Action;
  48300. })(BABYLON || (BABYLON = {}));
  48301. //# sourceMappingURL=babylon.action.js.map
  48302. var BABYLON;
  48303. (function (BABYLON) {
  48304. /**
  48305. * ActionEvent is the event beint sent when an action is triggered.
  48306. */
  48307. var ActionEvent = /** @class */ (function () {
  48308. /**
  48309. * @param source The mesh or sprite that triggered the action.
  48310. * @param pointerX The X mouse cursor position at the time of the event
  48311. * @param pointerY The Y mouse cursor position at the time of the event
  48312. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48313. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48314. */
  48315. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48316. this.source = source;
  48317. this.pointerX = pointerX;
  48318. this.pointerY = pointerY;
  48319. this.meshUnderPointer = meshUnderPointer;
  48320. this.sourceEvent = sourceEvent;
  48321. this.additionalData = additionalData;
  48322. }
  48323. /**
  48324. * Helper function to auto-create an ActionEvent from a source mesh.
  48325. * @param source The source mesh that triggered the event
  48326. * @param evt {Event} The original (browser) event
  48327. */
  48328. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48329. var scene = source.getScene();
  48330. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48331. };
  48332. /**
  48333. * Helper function to auto-create an ActionEvent from a source mesh.
  48334. * @param source The source sprite that triggered the event
  48335. * @param scene Scene associated with the sprite
  48336. * @param evt {Event} The original (browser) event
  48337. */
  48338. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48339. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48340. };
  48341. /**
  48342. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48343. * @param scene the scene where the event occurred
  48344. * @param evt {Event} The original (browser) event
  48345. */
  48346. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48347. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48348. };
  48349. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48350. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48351. };
  48352. return ActionEvent;
  48353. }());
  48354. BABYLON.ActionEvent = ActionEvent;
  48355. /**
  48356. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48357. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48358. */
  48359. var ActionManager = /** @class */ (function () {
  48360. function ActionManager(scene) {
  48361. // Members
  48362. this.actions = new Array();
  48363. this.hoverCursor = '';
  48364. this._scene = scene;
  48365. scene._actionManagers.push(this);
  48366. }
  48367. Object.defineProperty(ActionManager, "NothingTrigger", {
  48368. get: function () {
  48369. return ActionManager._NothingTrigger;
  48370. },
  48371. enumerable: true,
  48372. configurable: true
  48373. });
  48374. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48375. get: function () {
  48376. return ActionManager._OnPickTrigger;
  48377. },
  48378. enumerable: true,
  48379. configurable: true
  48380. });
  48381. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48382. get: function () {
  48383. return ActionManager._OnLeftPickTrigger;
  48384. },
  48385. enumerable: true,
  48386. configurable: true
  48387. });
  48388. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48389. get: function () {
  48390. return ActionManager._OnRightPickTrigger;
  48391. },
  48392. enumerable: true,
  48393. configurable: true
  48394. });
  48395. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48396. get: function () {
  48397. return ActionManager._OnCenterPickTrigger;
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48403. get: function () {
  48404. return ActionManager._OnPickDownTrigger;
  48405. },
  48406. enumerable: true,
  48407. configurable: true
  48408. });
  48409. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48410. get: function () {
  48411. return ActionManager._OnDoublePickTrigger;
  48412. },
  48413. enumerable: true,
  48414. configurable: true
  48415. });
  48416. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48417. get: function () {
  48418. return ActionManager._OnPickUpTrigger;
  48419. },
  48420. enumerable: true,
  48421. configurable: true
  48422. });
  48423. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48424. /// This trigger will only be raised if you also declared a OnPickDown
  48425. get: function () {
  48426. return ActionManager._OnPickOutTrigger;
  48427. },
  48428. enumerable: true,
  48429. configurable: true
  48430. });
  48431. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48432. get: function () {
  48433. return ActionManager._OnLongPressTrigger;
  48434. },
  48435. enumerable: true,
  48436. configurable: true
  48437. });
  48438. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48439. get: function () {
  48440. return ActionManager._OnPointerOverTrigger;
  48441. },
  48442. enumerable: true,
  48443. configurable: true
  48444. });
  48445. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48446. get: function () {
  48447. return ActionManager._OnPointerOutTrigger;
  48448. },
  48449. enumerable: true,
  48450. configurable: true
  48451. });
  48452. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48453. get: function () {
  48454. return ActionManager._OnEveryFrameTrigger;
  48455. },
  48456. enumerable: true,
  48457. configurable: true
  48458. });
  48459. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48460. get: function () {
  48461. return ActionManager._OnIntersectionEnterTrigger;
  48462. },
  48463. enumerable: true,
  48464. configurable: true
  48465. });
  48466. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48467. get: function () {
  48468. return ActionManager._OnIntersectionExitTrigger;
  48469. },
  48470. enumerable: true,
  48471. configurable: true
  48472. });
  48473. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48474. get: function () {
  48475. return ActionManager._OnKeyDownTrigger;
  48476. },
  48477. enumerable: true,
  48478. configurable: true
  48479. });
  48480. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48481. get: function () {
  48482. return ActionManager._OnKeyUpTrigger;
  48483. },
  48484. enumerable: true,
  48485. configurable: true
  48486. });
  48487. // Methods
  48488. ActionManager.prototype.dispose = function () {
  48489. var index = this._scene._actionManagers.indexOf(this);
  48490. for (var i = 0; i < this.actions.length; i++) {
  48491. var action = this.actions[i];
  48492. ActionManager.Triggers[action.trigger]--;
  48493. if (ActionManager.Triggers[action.trigger] === 0) {
  48494. delete ActionManager.Triggers[action.trigger];
  48495. }
  48496. }
  48497. if (index > -1) {
  48498. this._scene._actionManagers.splice(index, 1);
  48499. }
  48500. };
  48501. ActionManager.prototype.getScene = function () {
  48502. return this._scene;
  48503. };
  48504. /**
  48505. * Does this action manager handles actions of any of the given triggers
  48506. * @param {number[]} triggers - the triggers to be tested
  48507. * @return {boolean} whether one (or more) of the triggers is handeled
  48508. */
  48509. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48510. for (var index = 0; index < this.actions.length; index++) {
  48511. var action = this.actions[index];
  48512. if (triggers.indexOf(action.trigger) > -1) {
  48513. return true;
  48514. }
  48515. }
  48516. return false;
  48517. };
  48518. /**
  48519. * Does this action manager handles actions of a given trigger
  48520. * @param {number} trigger - the trigger to be tested
  48521. * @return {boolean} whether the trigger is handeled
  48522. */
  48523. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48524. for (var index = 0; index < this.actions.length; index++) {
  48525. var action = this.actions[index];
  48526. if (action.trigger === trigger) {
  48527. return true;
  48528. }
  48529. }
  48530. return false;
  48531. };
  48532. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48533. /**
  48534. * Does this action manager has pointer triggers
  48535. * @return {boolean} whether or not it has pointer triggers
  48536. */
  48537. get: function () {
  48538. for (var index = 0; index < this.actions.length; index++) {
  48539. var action = this.actions[index];
  48540. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48541. return true;
  48542. }
  48543. }
  48544. return false;
  48545. },
  48546. enumerable: true,
  48547. configurable: true
  48548. });
  48549. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48550. /**
  48551. * Does this action manager has pick triggers
  48552. * @return {boolean} whether or not it has pick triggers
  48553. */
  48554. get: function () {
  48555. for (var index = 0; index < this.actions.length; index++) {
  48556. var action = this.actions[index];
  48557. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48558. return true;
  48559. }
  48560. }
  48561. return false;
  48562. },
  48563. enumerable: true,
  48564. configurable: true
  48565. });
  48566. Object.defineProperty(ActionManager, "HasTriggers", {
  48567. /**
  48568. * Does exist one action manager with at least one trigger
  48569. * @return {boolean} whether or not it exists one action manager with one trigger
  48570. **/
  48571. get: function () {
  48572. for (var t in ActionManager.Triggers) {
  48573. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48574. return true;
  48575. }
  48576. }
  48577. return false;
  48578. },
  48579. enumerable: true,
  48580. configurable: true
  48581. });
  48582. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48583. /**
  48584. * Does exist one action manager with at least one pick trigger
  48585. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48586. **/
  48587. get: function () {
  48588. for (var t in ActionManager.Triggers) {
  48589. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48590. var t_int = parseInt(t);
  48591. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48592. return true;
  48593. }
  48594. }
  48595. }
  48596. return false;
  48597. },
  48598. enumerable: true,
  48599. configurable: true
  48600. });
  48601. /**
  48602. * Does exist one action manager that handles actions of a given trigger
  48603. * @param {number} trigger - the trigger to be tested
  48604. * @return {boolean} whether the trigger is handeled by at least one action manager
  48605. **/
  48606. ActionManager.HasSpecificTrigger = function (trigger) {
  48607. for (var t in ActionManager.Triggers) {
  48608. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48609. var t_int = parseInt(t);
  48610. if (t_int === trigger) {
  48611. return true;
  48612. }
  48613. }
  48614. }
  48615. return false;
  48616. };
  48617. /**
  48618. * Registers an action to this action manager
  48619. * @param {BABYLON.Action} action - the action to be registered
  48620. * @return {BABYLON.Action} the action amended (prepared) after registration
  48621. */
  48622. ActionManager.prototype.registerAction = function (action) {
  48623. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48624. if (this.getScene().actionManager !== this) {
  48625. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48626. return null;
  48627. }
  48628. }
  48629. this.actions.push(action);
  48630. if (ActionManager.Triggers[action.trigger]) {
  48631. ActionManager.Triggers[action.trigger]++;
  48632. }
  48633. else {
  48634. ActionManager.Triggers[action.trigger] = 1;
  48635. }
  48636. action._actionManager = this;
  48637. action._prepare();
  48638. return action;
  48639. };
  48640. /**
  48641. * Unregisters an action to this action manager
  48642. * @param action The action to be unregistered
  48643. * @return whether the action has been unregistered
  48644. */
  48645. ActionManager.prototype.unregisterAction = function (action) {
  48646. var index = this.actions.indexOf(action);
  48647. if (index !== -1) {
  48648. this.actions.splice(index, 1);
  48649. ActionManager.Triggers[action.trigger] -= 1;
  48650. if (ActionManager.Triggers[action.trigger] === 0) {
  48651. delete ActionManager.Triggers[action.trigger];
  48652. }
  48653. delete action._actionManager;
  48654. return true;
  48655. }
  48656. return false;
  48657. };
  48658. /**
  48659. * Process a specific trigger
  48660. * @param {number} trigger - the trigger to process
  48661. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48662. */
  48663. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48664. for (var index = 0; index < this.actions.length; index++) {
  48665. var action = this.actions[index];
  48666. if (action.trigger === trigger) {
  48667. if (evt) {
  48668. if (trigger === ActionManager.OnKeyUpTrigger
  48669. || trigger === ActionManager.OnKeyDownTrigger) {
  48670. var parameter = action.getTriggerParameter();
  48671. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48672. if (!parameter.toLowerCase) {
  48673. continue;
  48674. }
  48675. var lowerCase = parameter.toLowerCase();
  48676. if (lowerCase !== evt.sourceEvent.key) {
  48677. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48678. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48679. if (actualkey !== lowerCase) {
  48680. continue;
  48681. }
  48682. }
  48683. }
  48684. }
  48685. }
  48686. action._executeCurrent(evt);
  48687. }
  48688. }
  48689. };
  48690. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48691. var properties = propertyPath.split(".");
  48692. for (var index = 0; index < properties.length - 1; index++) {
  48693. target = target[properties[index]];
  48694. }
  48695. return target;
  48696. };
  48697. ActionManager.prototype._getProperty = function (propertyPath) {
  48698. var properties = propertyPath.split(".");
  48699. return properties[properties.length - 1];
  48700. };
  48701. ActionManager.prototype.serialize = function (name) {
  48702. var root = {
  48703. children: new Array(),
  48704. name: name,
  48705. type: 3,
  48706. properties: new Array() // Empty for root but required
  48707. };
  48708. for (var i = 0; i < this.actions.length; i++) {
  48709. var triggerObject = {
  48710. type: 0,
  48711. children: new Array(),
  48712. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48713. properties: new Array()
  48714. };
  48715. var triggerOptions = this.actions[i].triggerOptions;
  48716. if (triggerOptions && typeof triggerOptions !== "number") {
  48717. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48718. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48719. }
  48720. else {
  48721. var parameter = {};
  48722. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48723. if (triggerOptions.parameter.mesh) {
  48724. parameter._meshId = triggerOptions.parameter.mesh.id;
  48725. }
  48726. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48727. }
  48728. }
  48729. // Serialize child action, recursively
  48730. this.actions[i].serialize(triggerObject);
  48731. // Add serialized trigger
  48732. root.children.push(triggerObject);
  48733. }
  48734. return root;
  48735. };
  48736. ActionManager.Parse = function (parsedActions, object, scene) {
  48737. var actionManager = new ActionManager(scene);
  48738. if (object === null)
  48739. scene.actionManager = actionManager;
  48740. else
  48741. object.actionManager = actionManager;
  48742. // instanciate a new object
  48743. var instanciate = function (name, params) {
  48744. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48745. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48746. newInstance.constructor.apply(newInstance, params);
  48747. return newInstance;
  48748. };
  48749. var parseParameter = function (name, value, target, propertyPath) {
  48750. if (propertyPath === null) {
  48751. // String, boolean or float
  48752. var floatValue = parseFloat(value);
  48753. if (value === "true" || value === "false")
  48754. return value === "true";
  48755. else
  48756. return isNaN(floatValue) ? value : floatValue;
  48757. }
  48758. var effectiveTarget = propertyPath.split(".");
  48759. var values = value.split(",");
  48760. // Get effective Target
  48761. for (var i = 0; i < effectiveTarget.length; i++) {
  48762. target = target[effectiveTarget[i]];
  48763. }
  48764. // Return appropriate value with its type
  48765. if (typeof (target) === "boolean")
  48766. return values[0] === "true";
  48767. if (typeof (target) === "string")
  48768. return values[0];
  48769. // Parameters with multiple values such as Vector3 etc.
  48770. var split = new Array();
  48771. for (var i = 0; i < values.length; i++)
  48772. split.push(parseFloat(values[i]));
  48773. if (target instanceof BABYLON.Vector3)
  48774. return BABYLON.Vector3.FromArray(split);
  48775. if (target instanceof BABYLON.Vector4)
  48776. return BABYLON.Vector4.FromArray(split);
  48777. if (target instanceof BABYLON.Color3)
  48778. return BABYLON.Color3.FromArray(split);
  48779. if (target instanceof BABYLON.Color4)
  48780. return BABYLON.Color4.FromArray(split);
  48781. return parseFloat(values[0]);
  48782. };
  48783. // traverse graph per trigger
  48784. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48785. if (combineArray === void 0) { combineArray = null; }
  48786. if (parsedAction.detached)
  48787. return;
  48788. var parameters = new Array();
  48789. var target = null;
  48790. var propertyPath = null;
  48791. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48792. // Parameters
  48793. if (parsedAction.type === 2)
  48794. parameters.push(actionManager);
  48795. else
  48796. parameters.push(trigger);
  48797. if (combine) {
  48798. var actions = new Array();
  48799. for (var j = 0; j < parsedAction.combine.length; j++) {
  48800. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48801. }
  48802. parameters.push(actions);
  48803. }
  48804. else {
  48805. for (var i = 0; i < parsedAction.properties.length; i++) {
  48806. var value = parsedAction.properties[i].value;
  48807. var name = parsedAction.properties[i].name;
  48808. var targetType = parsedAction.properties[i].targetType;
  48809. if (name === "target")
  48810. if (targetType !== null && targetType === "SceneProperties")
  48811. value = target = scene;
  48812. else
  48813. value = target = scene.getNodeByName(value);
  48814. else if (name === "parent")
  48815. value = scene.getNodeByName(value);
  48816. else if (name === "sound")
  48817. value = scene.getSoundByName(value);
  48818. else if (name !== "propertyPath") {
  48819. if (parsedAction.type === 2 && name === "operator")
  48820. value = BABYLON.ValueCondition[value];
  48821. else
  48822. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48823. }
  48824. else {
  48825. propertyPath = value;
  48826. }
  48827. parameters.push(value);
  48828. }
  48829. }
  48830. if (combineArray === null) {
  48831. parameters.push(condition);
  48832. }
  48833. else {
  48834. parameters.push(null);
  48835. }
  48836. // If interpolate value action
  48837. if (parsedAction.name === "InterpolateValueAction") {
  48838. var param = parameters[parameters.length - 2];
  48839. parameters[parameters.length - 1] = param;
  48840. parameters[parameters.length - 2] = condition;
  48841. }
  48842. // Action or condition(s) and not CombineAction
  48843. var newAction = instanciate(parsedAction.name, parameters);
  48844. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48845. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48846. if (action)
  48847. action.then(nothing);
  48848. else
  48849. actionManager.registerAction(nothing);
  48850. action = nothing;
  48851. }
  48852. if (combineArray === null) {
  48853. if (newAction instanceof BABYLON.Condition) {
  48854. condition = newAction;
  48855. newAction = action;
  48856. }
  48857. else {
  48858. condition = null;
  48859. if (action)
  48860. action.then(newAction);
  48861. else
  48862. actionManager.registerAction(newAction);
  48863. }
  48864. }
  48865. else {
  48866. combineArray.push(newAction);
  48867. }
  48868. for (var i = 0; i < parsedAction.children.length; i++)
  48869. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48870. };
  48871. // triggers
  48872. for (var i = 0; i < parsedActions.children.length; i++) {
  48873. var triggerParams;
  48874. var trigger = parsedActions.children[i];
  48875. if (trigger.properties.length > 0) {
  48876. var param = trigger.properties[0].value;
  48877. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48878. if (value._meshId) {
  48879. value.mesh = scene.getMeshByID(value._meshId);
  48880. }
  48881. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48882. }
  48883. else
  48884. triggerParams = ActionManager[trigger.name];
  48885. for (var j = 0; j < trigger.children.length; j++) {
  48886. if (!trigger.detached)
  48887. traverse(trigger.children[j], triggerParams, null, null);
  48888. }
  48889. }
  48890. };
  48891. ActionManager.GetTriggerName = function (trigger) {
  48892. switch (trigger) {
  48893. case 0: return "NothingTrigger";
  48894. case 1: return "OnPickTrigger";
  48895. case 2: return "OnLeftPickTrigger";
  48896. case 3: return "OnRightPickTrigger";
  48897. case 4: return "OnCenterPickTrigger";
  48898. case 5: return "OnPickDownTrigger";
  48899. case 6: return "OnPickUpTrigger";
  48900. case 7: return "OnLongPressTrigger";
  48901. case 8: return "OnPointerOverTrigger";
  48902. case 9: return "OnPointerOutTrigger";
  48903. case 10: return "OnEveryFrameTrigger";
  48904. case 11: return "OnIntersectionEnterTrigger";
  48905. case 12: return "OnIntersectionExitTrigger";
  48906. case 13: return "OnKeyDownTrigger";
  48907. case 14: return "OnKeyUpTrigger";
  48908. case 15: return "OnPickOutTrigger";
  48909. default: return "";
  48910. }
  48911. };
  48912. // Statics
  48913. ActionManager._NothingTrigger = 0;
  48914. ActionManager._OnPickTrigger = 1;
  48915. ActionManager._OnLeftPickTrigger = 2;
  48916. ActionManager._OnRightPickTrigger = 3;
  48917. ActionManager._OnCenterPickTrigger = 4;
  48918. ActionManager._OnPickDownTrigger = 5;
  48919. ActionManager._OnDoublePickTrigger = 6;
  48920. ActionManager._OnPickUpTrigger = 7;
  48921. ActionManager._OnLongPressTrigger = 8;
  48922. ActionManager._OnPointerOverTrigger = 9;
  48923. ActionManager._OnPointerOutTrigger = 10;
  48924. ActionManager._OnEveryFrameTrigger = 11;
  48925. ActionManager._OnIntersectionEnterTrigger = 12;
  48926. ActionManager._OnIntersectionExitTrigger = 13;
  48927. ActionManager._OnKeyDownTrigger = 14;
  48928. ActionManager._OnKeyUpTrigger = 15;
  48929. ActionManager._OnPickOutTrigger = 16;
  48930. ActionManager.Triggers = {};
  48931. return ActionManager;
  48932. }());
  48933. BABYLON.ActionManager = ActionManager;
  48934. })(BABYLON || (BABYLON = {}));
  48935. //# sourceMappingURL=babylon.actionManager.js.map
  48936. var BABYLON;
  48937. (function (BABYLON) {
  48938. var InterpolateValueAction = /** @class */ (function (_super) {
  48939. __extends(InterpolateValueAction, _super);
  48940. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48941. if (duration === void 0) { duration = 1000; }
  48942. var _this = _super.call(this, triggerOptions, condition) || this;
  48943. _this.propertyPath = propertyPath;
  48944. _this.value = value;
  48945. _this.duration = duration;
  48946. _this.stopOtherAnimations = stopOtherAnimations;
  48947. _this.onInterpolationDone = onInterpolationDone;
  48948. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48949. _this._target = _this._effectiveTarget = target;
  48950. return _this;
  48951. }
  48952. InterpolateValueAction.prototype._prepare = function () {
  48953. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48954. this._property = this._getProperty(this.propertyPath);
  48955. };
  48956. InterpolateValueAction.prototype.execute = function () {
  48957. var _this = this;
  48958. var scene = this._actionManager.getScene();
  48959. var keys = [
  48960. {
  48961. frame: 0,
  48962. value: this._effectiveTarget[this._property]
  48963. }, {
  48964. frame: 100,
  48965. value: this.value
  48966. }
  48967. ];
  48968. var dataType;
  48969. if (typeof this.value === "number") {
  48970. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48971. }
  48972. else if (this.value instanceof BABYLON.Color3) {
  48973. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48974. }
  48975. else if (this.value instanceof BABYLON.Vector3) {
  48976. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48977. }
  48978. else if (this.value instanceof BABYLON.Matrix) {
  48979. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48980. }
  48981. else if (this.value instanceof BABYLON.Quaternion) {
  48982. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48983. }
  48984. else {
  48985. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48986. return;
  48987. }
  48988. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48989. animation.setKeys(keys);
  48990. if (this.stopOtherAnimations) {
  48991. scene.stopAnimation(this._effectiveTarget);
  48992. }
  48993. var wrapper = function () {
  48994. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48995. if (_this.onInterpolationDone) {
  48996. _this.onInterpolationDone();
  48997. }
  48998. };
  48999. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49000. };
  49001. InterpolateValueAction.prototype.serialize = function (parent) {
  49002. return _super.prototype._serialize.call(this, {
  49003. name: "InterpolateValueAction",
  49004. properties: [
  49005. BABYLON.Action._GetTargetProperty(this._target),
  49006. { name: "propertyPath", value: this.propertyPath },
  49007. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49008. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49009. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49010. ]
  49011. }, parent);
  49012. };
  49013. return InterpolateValueAction;
  49014. }(BABYLON.Action));
  49015. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49016. })(BABYLON || (BABYLON = {}));
  49017. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49018. var BABYLON;
  49019. (function (BABYLON) {
  49020. var SwitchBooleanAction = /** @class */ (function (_super) {
  49021. __extends(SwitchBooleanAction, _super);
  49022. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49023. var _this = _super.call(this, triggerOptions, condition) || this;
  49024. _this.propertyPath = propertyPath;
  49025. _this._target = _this._effectiveTarget = target;
  49026. return _this;
  49027. }
  49028. SwitchBooleanAction.prototype._prepare = function () {
  49029. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49030. this._property = this._getProperty(this.propertyPath);
  49031. };
  49032. SwitchBooleanAction.prototype.execute = function () {
  49033. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49034. };
  49035. SwitchBooleanAction.prototype.serialize = function (parent) {
  49036. return _super.prototype._serialize.call(this, {
  49037. name: "SwitchBooleanAction",
  49038. properties: [
  49039. BABYLON.Action._GetTargetProperty(this._target),
  49040. { name: "propertyPath", value: this.propertyPath }
  49041. ]
  49042. }, parent);
  49043. };
  49044. return SwitchBooleanAction;
  49045. }(BABYLON.Action));
  49046. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49047. var SetStateAction = /** @class */ (function (_super) {
  49048. __extends(SetStateAction, _super);
  49049. function SetStateAction(triggerOptions, target, value, condition) {
  49050. var _this = _super.call(this, triggerOptions, condition) || this;
  49051. _this.value = value;
  49052. _this._target = target;
  49053. return _this;
  49054. }
  49055. SetStateAction.prototype.execute = function () {
  49056. this._target.state = this.value;
  49057. };
  49058. SetStateAction.prototype.serialize = function (parent) {
  49059. return _super.prototype._serialize.call(this, {
  49060. name: "SetStateAction",
  49061. properties: [
  49062. BABYLON.Action._GetTargetProperty(this._target),
  49063. { name: "value", value: this.value }
  49064. ]
  49065. }, parent);
  49066. };
  49067. return SetStateAction;
  49068. }(BABYLON.Action));
  49069. BABYLON.SetStateAction = SetStateAction;
  49070. var SetValueAction = /** @class */ (function (_super) {
  49071. __extends(SetValueAction, _super);
  49072. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49073. var _this = _super.call(this, triggerOptions, condition) || this;
  49074. _this.propertyPath = propertyPath;
  49075. _this.value = value;
  49076. _this._target = _this._effectiveTarget = target;
  49077. return _this;
  49078. }
  49079. SetValueAction.prototype._prepare = function () {
  49080. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49081. this._property = this._getProperty(this.propertyPath);
  49082. };
  49083. SetValueAction.prototype.execute = function () {
  49084. this._effectiveTarget[this._property] = this.value;
  49085. if (this._target.markAsDirty) {
  49086. this._target.markAsDirty(this._property);
  49087. }
  49088. };
  49089. SetValueAction.prototype.serialize = function (parent) {
  49090. return _super.prototype._serialize.call(this, {
  49091. name: "SetValueAction",
  49092. properties: [
  49093. BABYLON.Action._GetTargetProperty(this._target),
  49094. { name: "propertyPath", value: this.propertyPath },
  49095. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49096. ]
  49097. }, parent);
  49098. };
  49099. return SetValueAction;
  49100. }(BABYLON.Action));
  49101. BABYLON.SetValueAction = SetValueAction;
  49102. var IncrementValueAction = /** @class */ (function (_super) {
  49103. __extends(IncrementValueAction, _super);
  49104. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49105. var _this = _super.call(this, triggerOptions, condition) || this;
  49106. _this.propertyPath = propertyPath;
  49107. _this.value = value;
  49108. _this._target = _this._effectiveTarget = target;
  49109. return _this;
  49110. }
  49111. IncrementValueAction.prototype._prepare = function () {
  49112. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49113. this._property = this._getProperty(this.propertyPath);
  49114. if (typeof this._effectiveTarget[this._property] !== "number") {
  49115. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49116. }
  49117. };
  49118. IncrementValueAction.prototype.execute = function () {
  49119. this._effectiveTarget[this._property] += this.value;
  49120. if (this._target.markAsDirty) {
  49121. this._target.markAsDirty(this._property);
  49122. }
  49123. };
  49124. IncrementValueAction.prototype.serialize = function (parent) {
  49125. return _super.prototype._serialize.call(this, {
  49126. name: "IncrementValueAction",
  49127. properties: [
  49128. BABYLON.Action._GetTargetProperty(this._target),
  49129. { name: "propertyPath", value: this.propertyPath },
  49130. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49131. ]
  49132. }, parent);
  49133. };
  49134. return IncrementValueAction;
  49135. }(BABYLON.Action));
  49136. BABYLON.IncrementValueAction = IncrementValueAction;
  49137. var PlayAnimationAction = /** @class */ (function (_super) {
  49138. __extends(PlayAnimationAction, _super);
  49139. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49140. var _this = _super.call(this, triggerOptions, condition) || this;
  49141. _this.from = from;
  49142. _this.to = to;
  49143. _this.loop = loop;
  49144. _this._target = target;
  49145. return _this;
  49146. }
  49147. PlayAnimationAction.prototype._prepare = function () {
  49148. };
  49149. PlayAnimationAction.prototype.execute = function () {
  49150. var scene = this._actionManager.getScene();
  49151. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49152. };
  49153. PlayAnimationAction.prototype.serialize = function (parent) {
  49154. return _super.prototype._serialize.call(this, {
  49155. name: "PlayAnimationAction",
  49156. properties: [
  49157. BABYLON.Action._GetTargetProperty(this._target),
  49158. { name: "from", value: String(this.from) },
  49159. { name: "to", value: String(this.to) },
  49160. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49161. ]
  49162. }, parent);
  49163. };
  49164. return PlayAnimationAction;
  49165. }(BABYLON.Action));
  49166. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49167. var StopAnimationAction = /** @class */ (function (_super) {
  49168. __extends(StopAnimationAction, _super);
  49169. function StopAnimationAction(triggerOptions, target, condition) {
  49170. var _this = _super.call(this, triggerOptions, condition) || this;
  49171. _this._target = target;
  49172. return _this;
  49173. }
  49174. StopAnimationAction.prototype._prepare = function () {
  49175. };
  49176. StopAnimationAction.prototype.execute = function () {
  49177. var scene = this._actionManager.getScene();
  49178. scene.stopAnimation(this._target);
  49179. };
  49180. StopAnimationAction.prototype.serialize = function (parent) {
  49181. return _super.prototype._serialize.call(this, {
  49182. name: "StopAnimationAction",
  49183. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49184. }, parent);
  49185. };
  49186. return StopAnimationAction;
  49187. }(BABYLON.Action));
  49188. BABYLON.StopAnimationAction = StopAnimationAction;
  49189. var DoNothingAction = /** @class */ (function (_super) {
  49190. __extends(DoNothingAction, _super);
  49191. function DoNothingAction(triggerOptions, condition) {
  49192. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49193. return _super.call(this, triggerOptions, condition) || this;
  49194. }
  49195. DoNothingAction.prototype.execute = function () {
  49196. };
  49197. DoNothingAction.prototype.serialize = function (parent) {
  49198. return _super.prototype._serialize.call(this, {
  49199. name: "DoNothingAction",
  49200. properties: []
  49201. }, parent);
  49202. };
  49203. return DoNothingAction;
  49204. }(BABYLON.Action));
  49205. BABYLON.DoNothingAction = DoNothingAction;
  49206. var CombineAction = /** @class */ (function (_super) {
  49207. __extends(CombineAction, _super);
  49208. function CombineAction(triggerOptions, children, condition) {
  49209. var _this = _super.call(this, triggerOptions, condition) || this;
  49210. _this.children = children;
  49211. return _this;
  49212. }
  49213. CombineAction.prototype._prepare = function () {
  49214. for (var index = 0; index < this.children.length; index++) {
  49215. this.children[index]._actionManager = this._actionManager;
  49216. this.children[index]._prepare();
  49217. }
  49218. };
  49219. CombineAction.prototype.execute = function (evt) {
  49220. for (var index = 0; index < this.children.length; index++) {
  49221. this.children[index].execute(evt);
  49222. }
  49223. };
  49224. CombineAction.prototype.serialize = function (parent) {
  49225. var serializationObject = _super.prototype._serialize.call(this, {
  49226. name: "CombineAction",
  49227. properties: [],
  49228. combine: []
  49229. }, parent);
  49230. for (var i = 0; i < this.children.length; i++) {
  49231. serializationObject.combine.push(this.children[i].serialize(null));
  49232. }
  49233. return serializationObject;
  49234. };
  49235. return CombineAction;
  49236. }(BABYLON.Action));
  49237. BABYLON.CombineAction = CombineAction;
  49238. var ExecuteCodeAction = /** @class */ (function (_super) {
  49239. __extends(ExecuteCodeAction, _super);
  49240. function ExecuteCodeAction(triggerOptions, func, condition) {
  49241. var _this = _super.call(this, triggerOptions, condition) || this;
  49242. _this.func = func;
  49243. return _this;
  49244. }
  49245. ExecuteCodeAction.prototype.execute = function (evt) {
  49246. this.func(evt);
  49247. };
  49248. return ExecuteCodeAction;
  49249. }(BABYLON.Action));
  49250. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49251. var SetParentAction = /** @class */ (function (_super) {
  49252. __extends(SetParentAction, _super);
  49253. function SetParentAction(triggerOptions, target, parent, condition) {
  49254. var _this = _super.call(this, triggerOptions, condition) || this;
  49255. _this._target = target;
  49256. _this._parent = parent;
  49257. return _this;
  49258. }
  49259. SetParentAction.prototype._prepare = function () {
  49260. };
  49261. SetParentAction.prototype.execute = function () {
  49262. if (this._target.parent === this._parent) {
  49263. return;
  49264. }
  49265. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49266. invertParentWorldMatrix.invert();
  49267. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49268. this._target.parent = this._parent;
  49269. };
  49270. SetParentAction.prototype.serialize = function (parent) {
  49271. return _super.prototype._serialize.call(this, {
  49272. name: "SetParentAction",
  49273. properties: [
  49274. BABYLON.Action._GetTargetProperty(this._target),
  49275. BABYLON.Action._GetTargetProperty(this._parent),
  49276. ]
  49277. }, parent);
  49278. };
  49279. return SetParentAction;
  49280. }(BABYLON.Action));
  49281. BABYLON.SetParentAction = SetParentAction;
  49282. var PlaySoundAction = /** @class */ (function (_super) {
  49283. __extends(PlaySoundAction, _super);
  49284. function PlaySoundAction(triggerOptions, sound, condition) {
  49285. var _this = _super.call(this, triggerOptions, condition) || this;
  49286. _this._sound = sound;
  49287. return _this;
  49288. }
  49289. PlaySoundAction.prototype._prepare = function () {
  49290. };
  49291. PlaySoundAction.prototype.execute = function () {
  49292. if (this._sound !== undefined)
  49293. this._sound.play();
  49294. };
  49295. PlaySoundAction.prototype.serialize = function (parent) {
  49296. return _super.prototype._serialize.call(this, {
  49297. name: "PlaySoundAction",
  49298. properties: [{ name: "sound", value: this._sound.name }]
  49299. }, parent);
  49300. };
  49301. return PlaySoundAction;
  49302. }(BABYLON.Action));
  49303. BABYLON.PlaySoundAction = PlaySoundAction;
  49304. var StopSoundAction = /** @class */ (function (_super) {
  49305. __extends(StopSoundAction, _super);
  49306. function StopSoundAction(triggerOptions, sound, condition) {
  49307. var _this = _super.call(this, triggerOptions, condition) || this;
  49308. _this._sound = sound;
  49309. return _this;
  49310. }
  49311. StopSoundAction.prototype._prepare = function () {
  49312. };
  49313. StopSoundAction.prototype.execute = function () {
  49314. if (this._sound !== undefined)
  49315. this._sound.stop();
  49316. };
  49317. StopSoundAction.prototype.serialize = function (parent) {
  49318. return _super.prototype._serialize.call(this, {
  49319. name: "StopSoundAction",
  49320. properties: [{ name: "sound", value: this._sound.name }]
  49321. }, parent);
  49322. };
  49323. return StopSoundAction;
  49324. }(BABYLON.Action));
  49325. BABYLON.StopSoundAction = StopSoundAction;
  49326. })(BABYLON || (BABYLON = {}));
  49327. //# sourceMappingURL=babylon.directActions.js.map
  49328. var BABYLON;
  49329. (function (BABYLON) {
  49330. var SpriteManager = /** @class */ (function () {
  49331. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49332. if (epsilon === void 0) { epsilon = 0.01; }
  49333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49334. this.name = name;
  49335. this.sprites = new Array();
  49336. this.renderingGroupId = 0;
  49337. this.layerMask = 0x0FFFFFFF;
  49338. this.fogEnabled = true;
  49339. this.isPickable = false;
  49340. /**
  49341. * An event triggered when the manager is disposed.
  49342. * @type {BABYLON.Observable}
  49343. */
  49344. this.onDisposeObservable = new BABYLON.Observable();
  49345. this._vertexBuffers = {};
  49346. this._capacity = capacity;
  49347. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49348. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49349. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49350. if (cellSize.width && cellSize.height) {
  49351. this.cellWidth = cellSize.width;
  49352. this.cellHeight = cellSize.height;
  49353. }
  49354. else if (cellSize !== undefined) {
  49355. this.cellWidth = cellSize;
  49356. this.cellHeight = cellSize;
  49357. }
  49358. else {
  49359. return;
  49360. }
  49361. this._epsilon = epsilon;
  49362. this._scene = scene;
  49363. this._scene.spriteManagers.push(this);
  49364. var indices = [];
  49365. var index = 0;
  49366. for (var count = 0; count < capacity; count++) {
  49367. indices.push(index);
  49368. indices.push(index + 1);
  49369. indices.push(index + 2);
  49370. indices.push(index);
  49371. indices.push(index + 2);
  49372. indices.push(index + 3);
  49373. index += 4;
  49374. }
  49375. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49376. // VBO
  49377. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49378. this._vertexData = new Float32Array(capacity * 16 * 4);
  49379. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49380. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49381. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49382. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49383. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49384. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49385. this._vertexBuffers["options"] = options;
  49386. this._vertexBuffers["cellInfo"] = cellInfo;
  49387. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49388. // Effects
  49389. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49390. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49391. }
  49392. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49393. set: function (callback) {
  49394. if (this._onDisposeObserver) {
  49395. this.onDisposeObservable.remove(this._onDisposeObserver);
  49396. }
  49397. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49398. },
  49399. enumerable: true,
  49400. configurable: true
  49401. });
  49402. Object.defineProperty(SpriteManager.prototype, "texture", {
  49403. get: function () {
  49404. return this._spriteTexture;
  49405. },
  49406. set: function (value) {
  49407. this._spriteTexture = value;
  49408. },
  49409. enumerable: true,
  49410. configurable: true
  49411. });
  49412. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49413. var arrayOffset = index * 16;
  49414. if (offsetX === 0)
  49415. offsetX = this._epsilon;
  49416. else if (offsetX === 1)
  49417. offsetX = 1 - this._epsilon;
  49418. if (offsetY === 0)
  49419. offsetY = this._epsilon;
  49420. else if (offsetY === 1)
  49421. offsetY = 1 - this._epsilon;
  49422. this._vertexData[arrayOffset] = sprite.position.x;
  49423. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49424. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49425. this._vertexData[arrayOffset + 3] = sprite.angle;
  49426. this._vertexData[arrayOffset + 4] = sprite.width;
  49427. this._vertexData[arrayOffset + 5] = sprite.height;
  49428. this._vertexData[arrayOffset + 6] = offsetX;
  49429. this._vertexData[arrayOffset + 7] = offsetY;
  49430. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49431. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49432. var offset = (sprite.cellIndex / rowSize) >> 0;
  49433. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49434. this._vertexData[arrayOffset + 11] = offset;
  49435. // Color
  49436. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49437. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49438. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49439. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49440. };
  49441. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49442. var count = Math.min(this._capacity, this.sprites.length);
  49443. var min = BABYLON.Vector3.Zero();
  49444. var max = BABYLON.Vector3.Zero();
  49445. var distance = Number.MAX_VALUE;
  49446. var currentSprite = null;
  49447. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49448. var cameraView = camera.getViewMatrix();
  49449. for (var index = 0; index < count; index++) {
  49450. var sprite = this.sprites[index];
  49451. if (!sprite) {
  49452. continue;
  49453. }
  49454. if (predicate) {
  49455. if (!predicate(sprite)) {
  49456. continue;
  49457. }
  49458. }
  49459. else if (!sprite.isPickable) {
  49460. continue;
  49461. }
  49462. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49463. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49464. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49465. if (ray.intersectsBoxMinMax(min, max)) {
  49466. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49467. if (distance > currentDistance) {
  49468. distance = currentDistance;
  49469. currentSprite = sprite;
  49470. if (fastCheck) {
  49471. break;
  49472. }
  49473. }
  49474. }
  49475. }
  49476. if (currentSprite) {
  49477. var result = new BABYLON.PickingInfo();
  49478. result.hit = true;
  49479. result.pickedSprite = currentSprite;
  49480. result.distance = distance;
  49481. return result;
  49482. }
  49483. return null;
  49484. };
  49485. SpriteManager.prototype.render = function () {
  49486. // Check
  49487. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49488. return;
  49489. var engine = this._scene.getEngine();
  49490. var baseSize = this._spriteTexture.getBaseSize();
  49491. // Sprites
  49492. var deltaTime = engine.getDeltaTime();
  49493. var max = Math.min(this._capacity, this.sprites.length);
  49494. var rowSize = baseSize.width / this.cellWidth;
  49495. var offset = 0;
  49496. for (var index = 0; index < max; index++) {
  49497. var sprite = this.sprites[index];
  49498. if (!sprite) {
  49499. continue;
  49500. }
  49501. sprite._animate(deltaTime);
  49502. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49503. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49504. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49505. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49506. }
  49507. this._buffer.update(this._vertexData);
  49508. // Render
  49509. var effect = this._effectBase;
  49510. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49511. effect = this._effectFog;
  49512. }
  49513. engine.enableEffect(effect);
  49514. var viewMatrix = this._scene.getViewMatrix();
  49515. effect.setTexture("diffuseSampler", this._spriteTexture);
  49516. effect.setMatrix("view", viewMatrix);
  49517. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49518. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49519. // Fog
  49520. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49521. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49522. effect.setColor3("vFogColor", this._scene.fogColor);
  49523. }
  49524. // VBOs
  49525. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49526. // Draw order
  49527. engine.setDepthFunctionToLessOrEqual();
  49528. effect.setBool("alphaTest", true);
  49529. engine.setColorWrite(false);
  49530. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49531. engine.setColorWrite(true);
  49532. effect.setBool("alphaTest", false);
  49533. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49534. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49535. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49536. };
  49537. SpriteManager.prototype.dispose = function () {
  49538. if (this._buffer) {
  49539. this._buffer.dispose();
  49540. this._buffer = null;
  49541. }
  49542. if (this._indexBuffer) {
  49543. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49544. this._indexBuffer = null;
  49545. }
  49546. if (this._spriteTexture) {
  49547. this._spriteTexture.dispose();
  49548. this._spriteTexture = null;
  49549. }
  49550. // Remove from scene
  49551. var index = this._scene.spriteManagers.indexOf(this);
  49552. this._scene.spriteManagers.splice(index, 1);
  49553. // Callback
  49554. this.onDisposeObservable.notifyObservers(this);
  49555. this.onDisposeObservable.clear();
  49556. };
  49557. return SpriteManager;
  49558. }());
  49559. BABYLON.SpriteManager = SpriteManager;
  49560. })(BABYLON || (BABYLON = {}));
  49561. //# sourceMappingURL=babylon.spriteManager.js.map
  49562. var BABYLON;
  49563. (function (BABYLON) {
  49564. var Sprite = /** @class */ (function () {
  49565. function Sprite(name, manager) {
  49566. this.name = name;
  49567. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49568. this.width = 1.0;
  49569. this.height = 1.0;
  49570. this.angle = 0;
  49571. this.cellIndex = 0;
  49572. this.invertU = 0;
  49573. this.invertV = 0;
  49574. this.animations = new Array();
  49575. this.isPickable = false;
  49576. this._animationStarted = false;
  49577. this._loopAnimation = false;
  49578. this._fromIndex = 0;
  49579. this._toIndex = 0;
  49580. this._delay = 0;
  49581. this._direction = 1;
  49582. this._time = 0;
  49583. this._manager = manager;
  49584. this._manager.sprites.push(this);
  49585. this.position = BABYLON.Vector3.Zero();
  49586. }
  49587. Object.defineProperty(Sprite.prototype, "size", {
  49588. get: function () {
  49589. return this.width;
  49590. },
  49591. set: function (value) {
  49592. this.width = value;
  49593. this.height = value;
  49594. },
  49595. enumerable: true,
  49596. configurable: true
  49597. });
  49598. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49599. this._fromIndex = from;
  49600. this._toIndex = to;
  49601. this._loopAnimation = loop;
  49602. this._delay = delay;
  49603. this._animationStarted = true;
  49604. this._direction = from < to ? 1 : -1;
  49605. this.cellIndex = from;
  49606. this._time = 0;
  49607. this._onAnimationEnd = onAnimationEnd;
  49608. };
  49609. Sprite.prototype.stopAnimation = function () {
  49610. this._animationStarted = false;
  49611. };
  49612. Sprite.prototype._animate = function (deltaTime) {
  49613. if (!this._animationStarted)
  49614. return;
  49615. this._time += deltaTime;
  49616. if (this._time > this._delay) {
  49617. this._time = this._time % this._delay;
  49618. this.cellIndex += this._direction;
  49619. if (this.cellIndex > this._toIndex) {
  49620. if (this._loopAnimation) {
  49621. this.cellIndex = this._fromIndex;
  49622. }
  49623. else {
  49624. this.cellIndex = this._toIndex;
  49625. this._animationStarted = false;
  49626. if (this._onAnimationEnd) {
  49627. this._onAnimationEnd();
  49628. }
  49629. if (this.disposeWhenFinishedAnimating) {
  49630. this.dispose();
  49631. }
  49632. }
  49633. }
  49634. }
  49635. };
  49636. Sprite.prototype.dispose = function () {
  49637. for (var i = 0; i < this._manager.sprites.length; i++) {
  49638. if (this._manager.sprites[i] == this) {
  49639. this._manager.sprites.splice(i, 1);
  49640. }
  49641. }
  49642. };
  49643. return Sprite;
  49644. }());
  49645. BABYLON.Sprite = Sprite;
  49646. })(BABYLON || (BABYLON = {}));
  49647. //# sourceMappingURL=babylon.sprite.js.map
  49648. var BABYLON;
  49649. (function (BABYLON) {
  49650. var IntersectionInfo = /** @class */ (function () {
  49651. function IntersectionInfo(bu, bv, distance) {
  49652. this.bu = bu;
  49653. this.bv = bv;
  49654. this.distance = distance;
  49655. this.faceId = 0;
  49656. this.subMeshId = 0;
  49657. }
  49658. return IntersectionInfo;
  49659. }());
  49660. BABYLON.IntersectionInfo = IntersectionInfo;
  49661. var PickingInfo = /** @class */ (function () {
  49662. function PickingInfo() {
  49663. this.hit = false;
  49664. this.distance = 0;
  49665. this.pickedPoint = null;
  49666. this.pickedMesh = null;
  49667. this.bu = 0;
  49668. this.bv = 0;
  49669. this.faceId = -1;
  49670. this.subMeshId = 0;
  49671. this.pickedSprite = null;
  49672. }
  49673. // Methods
  49674. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49675. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49676. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49677. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49678. return null;
  49679. }
  49680. var indices = this.pickedMesh.getIndices();
  49681. if (!indices) {
  49682. return null;
  49683. }
  49684. var result;
  49685. if (useVerticesNormals) {
  49686. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49687. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49688. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49689. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49690. normal0 = normal0.scale(this.bu);
  49691. normal1 = normal1.scale(this.bv);
  49692. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49693. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49694. }
  49695. else {
  49696. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49697. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49698. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49699. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49700. var p1p2 = vertex1.subtract(vertex2);
  49701. var p3p2 = vertex3.subtract(vertex2);
  49702. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49703. }
  49704. if (useWorldCoordinates) {
  49705. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49706. }
  49707. return BABYLON.Vector3.Normalize(result);
  49708. };
  49709. PickingInfo.prototype.getTextureCoordinates = function () {
  49710. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49711. return null;
  49712. }
  49713. var indices = this.pickedMesh.getIndices();
  49714. if (!indices) {
  49715. return null;
  49716. }
  49717. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49718. if (!uvs) {
  49719. return null;
  49720. }
  49721. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49722. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49723. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49724. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49725. uv1 = uv1.scale(this.bu);
  49726. uv2 = uv2.scale(this.bv);
  49727. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49728. };
  49729. return PickingInfo;
  49730. }());
  49731. BABYLON.PickingInfo = PickingInfo;
  49732. })(BABYLON || (BABYLON = {}));
  49733. //# sourceMappingURL=babylon.pickingInfo.js.map
  49734. var BABYLON;
  49735. (function (BABYLON) {
  49736. var Ray = /** @class */ (function () {
  49737. function Ray(origin, direction, length) {
  49738. if (length === void 0) { length = Number.MAX_VALUE; }
  49739. this.origin = origin;
  49740. this.direction = direction;
  49741. this.length = length;
  49742. }
  49743. // Methods
  49744. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49745. var d = 0.0;
  49746. var maxValue = Number.MAX_VALUE;
  49747. var inv;
  49748. var min;
  49749. var max;
  49750. var temp;
  49751. if (Math.abs(this.direction.x) < 0.0000001) {
  49752. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49753. return false;
  49754. }
  49755. }
  49756. else {
  49757. inv = 1.0 / this.direction.x;
  49758. min = (minimum.x - this.origin.x) * inv;
  49759. max = (maximum.x - this.origin.x) * inv;
  49760. if (max === -Infinity) {
  49761. max = Infinity;
  49762. }
  49763. if (min > max) {
  49764. temp = min;
  49765. min = max;
  49766. max = temp;
  49767. }
  49768. d = Math.max(min, d);
  49769. maxValue = Math.min(max, maxValue);
  49770. if (d > maxValue) {
  49771. return false;
  49772. }
  49773. }
  49774. if (Math.abs(this.direction.y) < 0.0000001) {
  49775. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49776. return false;
  49777. }
  49778. }
  49779. else {
  49780. inv = 1.0 / this.direction.y;
  49781. min = (minimum.y - this.origin.y) * inv;
  49782. max = (maximum.y - this.origin.y) * inv;
  49783. if (max === -Infinity) {
  49784. max = Infinity;
  49785. }
  49786. if (min > max) {
  49787. temp = min;
  49788. min = max;
  49789. max = temp;
  49790. }
  49791. d = Math.max(min, d);
  49792. maxValue = Math.min(max, maxValue);
  49793. if (d > maxValue) {
  49794. return false;
  49795. }
  49796. }
  49797. if (Math.abs(this.direction.z) < 0.0000001) {
  49798. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49799. return false;
  49800. }
  49801. }
  49802. else {
  49803. inv = 1.0 / this.direction.z;
  49804. min = (minimum.z - this.origin.z) * inv;
  49805. max = (maximum.z - this.origin.z) * inv;
  49806. if (max === -Infinity) {
  49807. max = Infinity;
  49808. }
  49809. if (min > max) {
  49810. temp = min;
  49811. min = max;
  49812. max = temp;
  49813. }
  49814. d = Math.max(min, d);
  49815. maxValue = Math.min(max, maxValue);
  49816. if (d > maxValue) {
  49817. return false;
  49818. }
  49819. }
  49820. return true;
  49821. };
  49822. Ray.prototype.intersectsBox = function (box) {
  49823. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49824. };
  49825. Ray.prototype.intersectsSphere = function (sphere) {
  49826. var x = sphere.center.x - this.origin.x;
  49827. var y = sphere.center.y - this.origin.y;
  49828. var z = sphere.center.z - this.origin.z;
  49829. var pyth = (x * x) + (y * y) + (z * z);
  49830. var rr = sphere.radius * sphere.radius;
  49831. if (pyth <= rr) {
  49832. return true;
  49833. }
  49834. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49835. if (dot < 0.0) {
  49836. return false;
  49837. }
  49838. var temp = pyth - (dot * dot);
  49839. return temp <= rr;
  49840. };
  49841. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49842. if (!this._edge1) {
  49843. this._edge1 = BABYLON.Vector3.Zero();
  49844. this._edge2 = BABYLON.Vector3.Zero();
  49845. this._pvec = BABYLON.Vector3.Zero();
  49846. this._tvec = BABYLON.Vector3.Zero();
  49847. this._qvec = BABYLON.Vector3.Zero();
  49848. }
  49849. vertex1.subtractToRef(vertex0, this._edge1);
  49850. vertex2.subtractToRef(vertex0, this._edge2);
  49851. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49852. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49853. if (det === 0) {
  49854. return null;
  49855. }
  49856. var invdet = 1 / det;
  49857. this.origin.subtractToRef(vertex0, this._tvec);
  49858. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49859. if (bu < 0 || bu > 1.0) {
  49860. return null;
  49861. }
  49862. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49863. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49864. if (bv < 0 || bu + bv > 1.0) {
  49865. return null;
  49866. }
  49867. //check if the distance is longer than the predefined length.
  49868. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49869. if (distance > this.length) {
  49870. return null;
  49871. }
  49872. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49873. };
  49874. Ray.prototype.intersectsPlane = function (plane) {
  49875. var distance;
  49876. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49877. if (Math.abs(result1) < 9.99999997475243E-07) {
  49878. return null;
  49879. }
  49880. else {
  49881. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49882. distance = (-plane.d - result2) / result1;
  49883. if (distance < 0.0) {
  49884. if (distance < -9.99999997475243E-07) {
  49885. return null;
  49886. }
  49887. else {
  49888. return 0;
  49889. }
  49890. }
  49891. return distance;
  49892. }
  49893. };
  49894. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49895. var tm = BABYLON.Tmp.Matrix[0];
  49896. mesh.getWorldMatrix().invertToRef(tm);
  49897. if (this._tmpRay) {
  49898. Ray.TransformToRef(this, tm, this._tmpRay);
  49899. }
  49900. else {
  49901. this._tmpRay = Ray.Transform(this, tm);
  49902. }
  49903. return mesh.intersects(this._tmpRay, fastCheck);
  49904. };
  49905. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49906. if (results) {
  49907. results.length = 0;
  49908. }
  49909. else {
  49910. results = [];
  49911. }
  49912. for (var i = 0; i < meshes.length; i++) {
  49913. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49914. if (pickInfo.hit) {
  49915. results.push(pickInfo);
  49916. }
  49917. }
  49918. results.sort(this._comparePickingInfo);
  49919. return results;
  49920. };
  49921. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49922. if (pickingInfoA.distance < pickingInfoB.distance) {
  49923. return -1;
  49924. }
  49925. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49926. return 1;
  49927. }
  49928. else {
  49929. return 0;
  49930. }
  49931. };
  49932. /**
  49933. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49934. * @param sega the first point of the segment to test the intersection against
  49935. * @param segb the second point of the segment to test the intersection against
  49936. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49937. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49938. */
  49939. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49940. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49941. var u = segb.subtract(sega);
  49942. var v = rsegb.subtract(this.origin);
  49943. var w = sega.subtract(this.origin);
  49944. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49945. var b = BABYLON.Vector3.Dot(u, v);
  49946. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49947. var d = BABYLON.Vector3.Dot(u, w);
  49948. var e = BABYLON.Vector3.Dot(v, w);
  49949. var D = a * c - b * b; // always >= 0
  49950. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49951. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49952. // compute the line parameters of the two closest points
  49953. if (D < Ray.smallnum) {
  49954. sN = 0.0; // force using point P0 on segment S1
  49955. sD = 1.0; // to prevent possible division by 0.0 later
  49956. tN = e;
  49957. tD = c;
  49958. }
  49959. else {
  49960. sN = (b * e - c * d);
  49961. tN = (a * e - b * d);
  49962. if (sN < 0.0) {
  49963. sN = 0.0;
  49964. tN = e;
  49965. tD = c;
  49966. }
  49967. else if (sN > sD) {
  49968. sN = sD;
  49969. tN = e + b;
  49970. tD = c;
  49971. }
  49972. }
  49973. if (tN < 0.0) {
  49974. tN = 0.0;
  49975. // recompute sc for this edge
  49976. if (-d < 0.0) {
  49977. sN = 0.0;
  49978. }
  49979. else if (-d > a)
  49980. sN = sD;
  49981. else {
  49982. sN = -d;
  49983. sD = a;
  49984. }
  49985. }
  49986. else if (tN > tD) {
  49987. tN = tD;
  49988. // recompute sc for this edge
  49989. if ((-d + b) < 0.0) {
  49990. sN = 0;
  49991. }
  49992. else if ((-d + b) > a) {
  49993. sN = sD;
  49994. }
  49995. else {
  49996. sN = (-d + b);
  49997. sD = a;
  49998. }
  49999. }
  50000. // finally do the division to get sc and tc
  50001. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50002. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50003. // get the difference of the two closest points
  50004. var qtc = v.multiplyByFloats(tc, tc, tc);
  50005. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50006. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50007. if (isIntersected) {
  50008. return qtc.length();
  50009. }
  50010. return -1;
  50011. };
  50012. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50013. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50014. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50015. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50016. this.direction.normalize();
  50017. return this;
  50018. };
  50019. // Statics
  50020. Ray.Zero = function () {
  50021. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50022. };
  50023. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50024. var result = Ray.Zero();
  50025. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50026. };
  50027. /**
  50028. * 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
  50029. * transformed to the given world matrix.
  50030. * @param origin The origin point
  50031. * @param end The end point
  50032. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50033. */
  50034. Ray.CreateNewFromTo = function (origin, end, world) {
  50035. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50036. var direction = end.subtract(origin);
  50037. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50038. direction.normalize();
  50039. return Ray.Transform(new Ray(origin, direction, length), world);
  50040. };
  50041. Ray.Transform = function (ray, matrix) {
  50042. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50043. Ray.TransformToRef(ray, matrix, result);
  50044. return result;
  50045. };
  50046. Ray.TransformToRef = function (ray, matrix, result) {
  50047. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50048. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50049. result.length = ray.length;
  50050. var dir = result.direction;
  50051. var len = dir.length();
  50052. if (!(len === 0 || len === 1)) {
  50053. var num = 1.0 / len;
  50054. dir.x *= num;
  50055. dir.y *= num;
  50056. dir.z *= num;
  50057. result.length *= len;
  50058. }
  50059. };
  50060. Ray.smallnum = 0.00000001;
  50061. Ray.rayl = 10e8;
  50062. return Ray;
  50063. }());
  50064. BABYLON.Ray = Ray;
  50065. })(BABYLON || (BABYLON = {}));
  50066. //# sourceMappingURL=babylon.ray.js.map
  50067. var BABYLON;
  50068. (function (BABYLON) {
  50069. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50070. if (boxMin.x > sphereCenter.x + sphereRadius)
  50071. return false;
  50072. if (sphereCenter.x - sphereRadius > boxMax.x)
  50073. return false;
  50074. if (boxMin.y > sphereCenter.y + sphereRadius)
  50075. return false;
  50076. if (sphereCenter.y - sphereRadius > boxMax.y)
  50077. return false;
  50078. if (boxMin.z > sphereCenter.z + sphereRadius)
  50079. return false;
  50080. if (sphereCenter.z - sphereRadius > boxMax.z)
  50081. return false;
  50082. return true;
  50083. };
  50084. var getLowestRoot = (function () {
  50085. var result = { root: 0, found: false };
  50086. return function (a, b, c, maxR) {
  50087. result.root = 0;
  50088. result.found = false;
  50089. var determinant = b * b - 4.0 * a * c;
  50090. if (determinant < 0)
  50091. return result;
  50092. var sqrtD = Math.sqrt(determinant);
  50093. var r1 = (-b - sqrtD) / (2.0 * a);
  50094. var r2 = (-b + sqrtD) / (2.0 * a);
  50095. if (r1 > r2) {
  50096. var temp = r2;
  50097. r2 = r1;
  50098. r1 = temp;
  50099. }
  50100. if (r1 > 0 && r1 < maxR) {
  50101. result.root = r1;
  50102. result.found = true;
  50103. return result;
  50104. }
  50105. if (r2 > 0 && r2 < maxR) {
  50106. result.root = r2;
  50107. result.found = true;
  50108. return result;
  50109. }
  50110. return result;
  50111. };
  50112. })();
  50113. var Collider = /** @class */ (function () {
  50114. function Collider() {
  50115. this._collisionPoint = BABYLON.Vector3.Zero();
  50116. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50117. this._tempVector = BABYLON.Vector3.Zero();
  50118. this._tempVector2 = BABYLON.Vector3.Zero();
  50119. this._tempVector3 = BABYLON.Vector3.Zero();
  50120. this._tempVector4 = BABYLON.Vector3.Zero();
  50121. this._edge = BABYLON.Vector3.Zero();
  50122. this._baseToVertex = BABYLON.Vector3.Zero();
  50123. this._destinationPoint = BABYLON.Vector3.Zero();
  50124. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50125. this._displacementVector = BABYLON.Vector3.Zero();
  50126. this._radius = BABYLON.Vector3.One();
  50127. this._retry = 0;
  50128. this._basePointWorld = BABYLON.Vector3.Zero();
  50129. this._velocityWorld = BABYLON.Vector3.Zero();
  50130. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50131. this._collisionMask = -1;
  50132. }
  50133. Object.defineProperty(Collider.prototype, "collisionMask", {
  50134. get: function () {
  50135. return this._collisionMask;
  50136. },
  50137. set: function (mask) {
  50138. this._collisionMask = !isNaN(mask) ? mask : -1;
  50139. },
  50140. enumerable: true,
  50141. configurable: true
  50142. });
  50143. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50144. /**
  50145. * Gets the plane normal used to compute the sliding response (in local space)
  50146. */
  50147. get: function () {
  50148. return this._slidePlaneNormal;
  50149. },
  50150. enumerable: true,
  50151. configurable: true
  50152. });
  50153. // Methods
  50154. Collider.prototype._initialize = function (source, dir, e) {
  50155. this._velocity = dir;
  50156. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50157. this._basePoint = source;
  50158. source.multiplyToRef(this._radius, this._basePointWorld);
  50159. dir.multiplyToRef(this._radius, this._velocityWorld);
  50160. this._velocityWorldLength = this._velocityWorld.length();
  50161. this._epsilon = e;
  50162. this.collisionFound = false;
  50163. };
  50164. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50165. pa.subtractToRef(point, this._tempVector);
  50166. pb.subtractToRef(point, this._tempVector2);
  50167. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50168. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50169. if (d < 0)
  50170. return false;
  50171. pc.subtractToRef(point, this._tempVector3);
  50172. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50173. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50174. if (d < 0)
  50175. return false;
  50176. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50177. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50178. return d >= 0;
  50179. };
  50180. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50181. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50182. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50183. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50184. return false;
  50185. }
  50186. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50187. return false;
  50188. return true;
  50189. };
  50190. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50191. var t0;
  50192. var embeddedInPlane = false;
  50193. //defensive programming, actually not needed.
  50194. if (!trianglePlaneArray) {
  50195. trianglePlaneArray = [];
  50196. }
  50197. if (!trianglePlaneArray[faceIndex]) {
  50198. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50199. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50200. }
  50201. var trianglePlane = trianglePlaneArray[faceIndex];
  50202. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50203. return;
  50204. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50205. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50206. if (normalDotVelocity == 0) {
  50207. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50208. return;
  50209. embeddedInPlane = true;
  50210. t0 = 0;
  50211. }
  50212. else {
  50213. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50214. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50215. if (t0 > t1) {
  50216. var temp = t1;
  50217. t1 = t0;
  50218. t0 = temp;
  50219. }
  50220. if (t0 > 1.0 || t1 < 0.0)
  50221. return;
  50222. if (t0 < 0)
  50223. t0 = 0;
  50224. if (t0 > 1.0)
  50225. t0 = 1.0;
  50226. }
  50227. this._collisionPoint.copyFromFloats(0, 0, 0);
  50228. var found = false;
  50229. var t = 1.0;
  50230. if (!embeddedInPlane) {
  50231. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50232. this._velocity.scaleToRef(t0, this._tempVector);
  50233. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50234. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50235. found = true;
  50236. t = t0;
  50237. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50238. }
  50239. }
  50240. if (!found) {
  50241. var velocitySquaredLength = this._velocity.lengthSquared();
  50242. var a = velocitySquaredLength;
  50243. this._basePoint.subtractToRef(p1, this._tempVector);
  50244. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50245. var c = this._tempVector.lengthSquared() - 1.0;
  50246. var lowestRoot = getLowestRoot(a, b, c, t);
  50247. if (lowestRoot.found) {
  50248. t = lowestRoot.root;
  50249. found = true;
  50250. this._collisionPoint.copyFrom(p1);
  50251. }
  50252. this._basePoint.subtractToRef(p2, this._tempVector);
  50253. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50254. c = this._tempVector.lengthSquared() - 1.0;
  50255. lowestRoot = getLowestRoot(a, b, c, t);
  50256. if (lowestRoot.found) {
  50257. t = lowestRoot.root;
  50258. found = true;
  50259. this._collisionPoint.copyFrom(p2);
  50260. }
  50261. this._basePoint.subtractToRef(p3, this._tempVector);
  50262. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50263. c = this._tempVector.lengthSquared() - 1.0;
  50264. lowestRoot = getLowestRoot(a, b, c, t);
  50265. if (lowestRoot.found) {
  50266. t = lowestRoot.root;
  50267. found = true;
  50268. this._collisionPoint.copyFrom(p3);
  50269. }
  50270. p2.subtractToRef(p1, this._edge);
  50271. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50272. var edgeSquaredLength = this._edge.lengthSquared();
  50273. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50274. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50275. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50276. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50277. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50278. lowestRoot = getLowestRoot(a, b, c, t);
  50279. if (lowestRoot.found) {
  50280. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50281. if (f >= 0.0 && f <= 1.0) {
  50282. t = lowestRoot.root;
  50283. found = true;
  50284. this._edge.scaleInPlace(f);
  50285. p1.addToRef(this._edge, this._collisionPoint);
  50286. }
  50287. }
  50288. p3.subtractToRef(p2, this._edge);
  50289. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50290. edgeSquaredLength = this._edge.lengthSquared();
  50291. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50292. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50293. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50294. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50295. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50296. lowestRoot = getLowestRoot(a, b, c, t);
  50297. if (lowestRoot.found) {
  50298. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50299. if (f >= 0.0 && f <= 1.0) {
  50300. t = lowestRoot.root;
  50301. found = true;
  50302. this._edge.scaleInPlace(f);
  50303. p2.addToRef(this._edge, this._collisionPoint);
  50304. }
  50305. }
  50306. p1.subtractToRef(p3, this._edge);
  50307. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50308. edgeSquaredLength = this._edge.lengthSquared();
  50309. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50310. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50311. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50312. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50313. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50314. lowestRoot = getLowestRoot(a, b, c, t);
  50315. if (lowestRoot.found) {
  50316. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50317. if (f >= 0.0 && f <= 1.0) {
  50318. t = lowestRoot.root;
  50319. found = true;
  50320. this._edge.scaleInPlace(f);
  50321. p3.addToRef(this._edge, this._collisionPoint);
  50322. }
  50323. }
  50324. }
  50325. if (found) {
  50326. var distToCollision = t * this._velocity.length();
  50327. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50328. if (!this.intersectionPoint) {
  50329. this.intersectionPoint = this._collisionPoint.clone();
  50330. }
  50331. else {
  50332. this.intersectionPoint.copyFrom(this._collisionPoint);
  50333. }
  50334. this._nearestDistance = distToCollision;
  50335. this.collisionFound = true;
  50336. }
  50337. }
  50338. };
  50339. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50340. for (var i = indexStart; i < indexEnd; i += 3) {
  50341. var p1 = pts[indices[i] - decal];
  50342. var p2 = pts[indices[i + 1] - decal];
  50343. var p3 = pts[indices[i + 2] - decal];
  50344. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50345. }
  50346. };
  50347. Collider.prototype._getResponse = function (pos, vel) {
  50348. pos.addToRef(vel, this._destinationPoint);
  50349. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50350. this._basePoint.addToRef(vel, pos);
  50351. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50352. this._slidePlaneNormal.normalize();
  50353. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50354. pos.addInPlace(this._displacementVector);
  50355. this.intersectionPoint.addInPlace(this._displacementVector);
  50356. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50357. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50358. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50359. };
  50360. return Collider;
  50361. }());
  50362. BABYLON.Collider = Collider;
  50363. })(BABYLON || (BABYLON = {}));
  50364. //# sourceMappingURL=babylon.collider.js.map
  50365. var BABYLON;
  50366. (function (BABYLON) {
  50367. //WebWorker code will be inserted to this variable.
  50368. BABYLON.CollisionWorker = "";
  50369. var WorkerTaskType;
  50370. (function (WorkerTaskType) {
  50371. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50372. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50373. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50374. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50375. var WorkerReplyType;
  50376. (function (WorkerReplyType) {
  50377. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50378. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50379. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50380. var CollisionCoordinatorWorker = /** @class */ (function () {
  50381. function CollisionCoordinatorWorker() {
  50382. var _this = this;
  50383. this._scaledPosition = BABYLON.Vector3.Zero();
  50384. this._scaledVelocity = BABYLON.Vector3.Zero();
  50385. this.onMeshUpdated = function (transformNode) {
  50386. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50387. };
  50388. this.onGeometryUpdated = function (geometry) {
  50389. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50390. };
  50391. this._afterRender = function () {
  50392. if (!_this._init)
  50393. return;
  50394. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50395. return;
  50396. }
  50397. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50398. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50399. if (_this._runningUpdated > 4) {
  50400. return;
  50401. }
  50402. ++_this._runningUpdated;
  50403. var payload = {
  50404. updatedMeshes: _this._addUpdateMeshesList,
  50405. updatedGeometries: _this._addUpdateGeometriesList,
  50406. removedGeometries: _this._toRemoveGeometryArray,
  50407. removedMeshes: _this._toRemoveMeshesArray
  50408. };
  50409. var message = {
  50410. payload: payload,
  50411. taskType: WorkerTaskType.UPDATE
  50412. };
  50413. var serializable = [];
  50414. for (var id in payload.updatedGeometries) {
  50415. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50416. //prepare transferables
  50417. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50418. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50419. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50420. }
  50421. }
  50422. _this._worker.postMessage(message, serializable);
  50423. _this._addUpdateMeshesList = {};
  50424. _this._addUpdateGeometriesList = {};
  50425. _this._toRemoveGeometryArray = [];
  50426. _this._toRemoveMeshesArray = [];
  50427. };
  50428. this._onMessageFromWorker = function (e) {
  50429. var returnData = e.data;
  50430. if (returnData.error != WorkerReplyType.SUCCESS) {
  50431. //TODO what errors can be returned from the worker?
  50432. BABYLON.Tools.Warn("error returned from worker!");
  50433. return;
  50434. }
  50435. switch (returnData.taskType) {
  50436. case WorkerTaskType.INIT:
  50437. _this._init = true;
  50438. //Update the worked with ALL of the scene's current state
  50439. _this._scene.meshes.forEach(function (mesh) {
  50440. _this.onMeshAdded(mesh);
  50441. });
  50442. _this._scene.getGeometries().forEach(function (geometry) {
  50443. _this.onGeometryAdded(geometry);
  50444. });
  50445. break;
  50446. case WorkerTaskType.UPDATE:
  50447. _this._runningUpdated--;
  50448. break;
  50449. case WorkerTaskType.COLLIDE:
  50450. var returnPayload = returnData.payload;
  50451. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50452. return;
  50453. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50454. if (callback) {
  50455. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50456. if (mesh) {
  50457. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50458. }
  50459. }
  50460. //cleanup
  50461. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50462. break;
  50463. }
  50464. };
  50465. this._collisionsCallbackArray = [];
  50466. this._init = false;
  50467. this._runningUpdated = 0;
  50468. this._addUpdateMeshesList = {};
  50469. this._addUpdateGeometriesList = {};
  50470. this._toRemoveGeometryArray = [];
  50471. this._toRemoveMeshesArray = [];
  50472. }
  50473. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50474. if (!this._init)
  50475. return;
  50476. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50477. return;
  50478. position.divideToRef(collider._radius, this._scaledPosition);
  50479. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50480. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50481. var payload = {
  50482. collider: {
  50483. position: this._scaledPosition.asArray(),
  50484. velocity: this._scaledVelocity.asArray(),
  50485. radius: collider._radius.asArray()
  50486. },
  50487. collisionId: collisionIndex,
  50488. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50489. maximumRetry: maximumRetry
  50490. };
  50491. var message = {
  50492. payload: payload,
  50493. taskType: WorkerTaskType.COLLIDE
  50494. };
  50495. this._worker.postMessage(message);
  50496. };
  50497. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50498. this._scene = scene;
  50499. this._scene.registerAfterRender(this._afterRender);
  50500. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50501. this._worker = new Worker(workerUrl);
  50502. this._worker.onmessage = this._onMessageFromWorker;
  50503. var message = {
  50504. payload: {},
  50505. taskType: WorkerTaskType.INIT
  50506. };
  50507. this._worker.postMessage(message);
  50508. };
  50509. CollisionCoordinatorWorker.prototype.destroy = function () {
  50510. this._scene.unregisterAfterRender(this._afterRender);
  50511. this._worker.terminate();
  50512. };
  50513. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50514. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50515. this.onMeshUpdated(mesh);
  50516. };
  50517. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50518. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50519. };
  50520. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50521. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50522. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50523. this.onGeometryUpdated(geometry);
  50524. };
  50525. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50526. this._toRemoveGeometryArray.push(geometry.id);
  50527. };
  50528. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50529. var submeshes = [];
  50530. if (mesh.subMeshes) {
  50531. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50532. var boundingInfo = sm.getBoundingInfo();
  50533. return {
  50534. position: idx,
  50535. verticesStart: sm.verticesStart,
  50536. verticesCount: sm.verticesCount,
  50537. indexStart: sm.indexStart,
  50538. indexCount: sm.indexCount,
  50539. hasMaterial: !!sm.getMaterial(),
  50540. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50541. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50542. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50543. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50544. };
  50545. });
  50546. }
  50547. var geometryId = null;
  50548. if (mesh instanceof BABYLON.Mesh) {
  50549. var geometry = mesh.geometry;
  50550. geometryId = geometry ? geometry.id : null;
  50551. }
  50552. else if (mesh instanceof BABYLON.InstancedMesh) {
  50553. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50554. geometryId = geometry ? geometry.id : null;
  50555. }
  50556. var boundingInfo = mesh.getBoundingInfo();
  50557. return {
  50558. uniqueId: mesh.uniqueId,
  50559. id: mesh.id,
  50560. name: mesh.name,
  50561. geometryId: geometryId,
  50562. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50563. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50564. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50565. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50566. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50567. subMeshes: submeshes,
  50568. checkCollisions: mesh.checkCollisions
  50569. };
  50570. };
  50571. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50572. return {
  50573. id: geometry.id,
  50574. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50575. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50576. indices: new Uint32Array(geometry.getIndices() || []),
  50577. };
  50578. };
  50579. return CollisionCoordinatorWorker;
  50580. }());
  50581. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50582. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50583. function CollisionCoordinatorLegacy() {
  50584. this._scaledPosition = BABYLON.Vector3.Zero();
  50585. this._scaledVelocity = BABYLON.Vector3.Zero();
  50586. this._finalPosition = BABYLON.Vector3.Zero();
  50587. }
  50588. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50589. position.divideToRef(collider._radius, this._scaledPosition);
  50590. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50591. collider.collidedMesh = null;
  50592. collider._retry = 0;
  50593. collider._initialVelocity = this._scaledVelocity;
  50594. collider._initialPosition = this._scaledPosition;
  50595. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50596. this._finalPosition.multiplyInPlace(collider._radius);
  50597. //run the callback
  50598. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50599. };
  50600. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50601. this._scene = scene;
  50602. };
  50603. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50604. //Legacy need no destruction method.
  50605. };
  50606. //No update in legacy mode
  50607. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50608. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50609. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50610. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50611. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50612. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50613. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50614. if (excludedMesh === void 0) { excludedMesh = null; }
  50615. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50616. if (collider._retry >= maximumRetry) {
  50617. finalPosition.copyFrom(position);
  50618. return;
  50619. }
  50620. // Check if this is a mesh else camera or -1
  50621. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50622. collider._initialize(position, velocity, closeDistance);
  50623. // Check all meshes
  50624. for (var index = 0; index < this._scene.meshes.length; index++) {
  50625. var mesh = this._scene.meshes[index];
  50626. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50627. mesh._checkCollision(collider);
  50628. }
  50629. }
  50630. if (!collider.collisionFound) {
  50631. position.addToRef(velocity, finalPosition);
  50632. return;
  50633. }
  50634. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50635. collider._getResponse(position, velocity);
  50636. }
  50637. if (velocity.length() <= closeDistance) {
  50638. finalPosition.copyFrom(position);
  50639. return;
  50640. }
  50641. collider._retry++;
  50642. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50643. };
  50644. return CollisionCoordinatorLegacy;
  50645. }());
  50646. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50647. })(BABYLON || (BABYLON = {}));
  50648. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50649. var BABYLON;
  50650. (function (BABYLON) {
  50651. /**
  50652. * A particle represents one of the element emitted by a particle system.
  50653. * This is mainly define by its coordinates, direction, velocity and age.
  50654. */
  50655. var Particle = /** @class */ (function () {
  50656. /**
  50657. * Creates a new instance of @see Particle
  50658. * @param particleSystem the particle system the particle belongs to
  50659. */
  50660. function Particle(
  50661. /**
  50662. * particleSystem the particle system the particle belongs to.
  50663. */
  50664. particleSystem) {
  50665. this.particleSystem = particleSystem;
  50666. /**
  50667. * The world position of the particle in the scene.
  50668. */
  50669. this.position = BABYLON.Vector3.Zero();
  50670. /**
  50671. * The world direction of the particle in the scene.
  50672. */
  50673. this.direction = BABYLON.Vector3.Zero();
  50674. /**
  50675. * The color of the particle.
  50676. */
  50677. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50678. /**
  50679. * The color change of the particle per step.
  50680. */
  50681. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50682. /**
  50683. * Defines how long will the life of the particle be.
  50684. */
  50685. this.lifeTime = 1.0;
  50686. /**
  50687. * The current age of the particle.
  50688. */
  50689. this.age = 0;
  50690. /**
  50691. * The current size of the particle.
  50692. */
  50693. this.size = 0;
  50694. /**
  50695. * The current angle of the particle.
  50696. */
  50697. this.angle = 0;
  50698. /**
  50699. * Defines how fast is the angle changing.
  50700. */
  50701. this.angularSpeed = 0;
  50702. /**
  50703. * Defines the cell index used by the particle to be rendered from a sprite.
  50704. */
  50705. this.cellIndex = 0;
  50706. this._currentFrameCounter = 0;
  50707. if (!this.particleSystem.isAnimationSheetEnabled) {
  50708. return;
  50709. }
  50710. this.updateCellInfoFromSystem();
  50711. }
  50712. Particle.prototype.updateCellInfoFromSystem = function () {
  50713. this.cellIndex = this.particleSystem.startSpriteCellID;
  50714. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50715. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50716. }
  50717. else {
  50718. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50719. }
  50720. };
  50721. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50722. // (ageOffset / scaledUpdateSpeed) / available cells
  50723. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50724. this._currentFrameCounter += scaledUpdateSpeed;
  50725. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50726. this._currentFrameCounter = 0;
  50727. this.cellIndex++;
  50728. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50729. this.cellIndex = this.particleSystem.endSpriteCellID;
  50730. }
  50731. }
  50732. };
  50733. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50734. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50735. this.cellIndex++;
  50736. this._currentFrameCounter = 0;
  50737. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50738. if (this.particleSystem.spriteCellLoop) {
  50739. this.cellIndex = this.particleSystem.startSpriteCellID;
  50740. }
  50741. else {
  50742. this.cellIndex = this.particleSystem.endSpriteCellID;
  50743. }
  50744. }
  50745. }
  50746. else {
  50747. this._currentFrameCounter++;
  50748. }
  50749. };
  50750. /**
  50751. * Copy the properties of particle to another one.
  50752. * @param other the particle to copy the information to.
  50753. */
  50754. Particle.prototype.copyTo = function (other) {
  50755. other.position.copyFrom(this.position);
  50756. other.direction.copyFrom(this.direction);
  50757. other.color.copyFrom(this.color);
  50758. other.colorStep.copyFrom(this.colorStep);
  50759. other.lifeTime = this.lifeTime;
  50760. other.age = this.age;
  50761. other.size = this.size;
  50762. other.angle = this.angle;
  50763. other.angularSpeed = this.angularSpeed;
  50764. other.particleSystem = this.particleSystem;
  50765. other.cellIndex = this.cellIndex;
  50766. };
  50767. return Particle;
  50768. }());
  50769. BABYLON.Particle = Particle;
  50770. })(BABYLON || (BABYLON = {}));
  50771. //# sourceMappingURL=babylon.particle.js.map
  50772. var BABYLON;
  50773. (function (BABYLON) {
  50774. /**
  50775. * This represents a particle system in Babylon.
  50776. * 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.
  50777. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50778. * @example https://doc.babylonjs.com/babylon101/particles
  50779. */
  50780. var ParticleSystem = /** @class */ (function () {
  50781. /**
  50782. * Instantiates a particle system.
  50783. * 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.
  50784. * @param name The name of the particle system
  50785. * @param capacity The max number of particles alive at the same time
  50786. * @param scene The scene the particle system belongs to
  50787. * @param customEffect a custom effect used to change the way particles are rendered by default
  50788. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50789. * @param epsilon Offset used to render the particles
  50790. */
  50791. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50792. if (customEffect === void 0) { customEffect = null; }
  50793. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50794. if (epsilon === void 0) { epsilon = 0.01; }
  50795. var _this = this;
  50796. /**
  50797. * List of animations used by the particle system.
  50798. */
  50799. this.animations = [];
  50800. /**
  50801. * The rendering group used by the Particle system to chose when to render.
  50802. */
  50803. this.renderingGroupId = 0;
  50804. /**
  50805. * The emitter represents the Mesh or position we are attaching the particle system to.
  50806. */
  50807. this.emitter = null;
  50808. /**
  50809. * The maximum number of particles to emit per frame
  50810. */
  50811. this.emitRate = 10;
  50812. /**
  50813. * If you want to launch only a few particles at once, that can be done, as well.
  50814. */
  50815. this.manualEmitCount = -1;
  50816. /**
  50817. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50818. */
  50819. this.updateSpeed = 0.01;
  50820. /**
  50821. * The amount of time the particle system is running (depends of the overall update speed).
  50822. */
  50823. this.targetStopDuration = 0;
  50824. /**
  50825. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50826. */
  50827. this.disposeOnStop = false;
  50828. /**
  50829. * Minimum power of emitting particles.
  50830. */
  50831. this.minEmitPower = 1;
  50832. /**
  50833. * Maximum power of emitting particles.
  50834. */
  50835. this.maxEmitPower = 1;
  50836. /**
  50837. * Minimum life time of emitting particles.
  50838. */
  50839. this.minLifeTime = 1;
  50840. /**
  50841. * Maximum life time of emitting particles.
  50842. */
  50843. this.maxLifeTime = 1;
  50844. /**
  50845. * Minimum Size of emitting particles.
  50846. */
  50847. this.minSize = 1;
  50848. /**
  50849. * Maximum Size of emitting particles.
  50850. */
  50851. this.maxSize = 1;
  50852. /**
  50853. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50854. */
  50855. this.minAngularSpeed = 0;
  50856. /**
  50857. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50858. */
  50859. this.maxAngularSpeed = 0;
  50860. /**
  50861. * The layer mask we are rendering the particles through.
  50862. */
  50863. this.layerMask = 0x0FFFFFFF;
  50864. /**
  50865. * This can help using your own shader to render the particle system.
  50866. * The according effect will be created
  50867. */
  50868. this.customShader = null;
  50869. /**
  50870. * By default particle system starts as soon as they are created. This prevents the
  50871. * automatic start to happen and let you decide when to start emitting particles.
  50872. */
  50873. this.preventAutoStart = false;
  50874. /**
  50875. * Callback triggered when the particle animation is ending.
  50876. */
  50877. this.onAnimationEnd = null;
  50878. /**
  50879. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50880. */
  50881. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50882. /**
  50883. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50884. * to override the particles.
  50885. */
  50886. this.forceDepthWrite = false;
  50887. /**
  50888. * You can use gravity if you want to give an orientation to your particles.
  50889. */
  50890. this.gravity = BABYLON.Vector3.Zero();
  50891. /**
  50892. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50893. */
  50894. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50895. /**
  50896. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50897. */
  50898. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50899. /**
  50900. * Color the particle will have at the end of its lifetime.
  50901. */
  50902. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50903. /**
  50904. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50905. */
  50906. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50907. /**
  50908. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50909. */
  50910. this.spriteCellLoop = true;
  50911. /**
  50912. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50913. */
  50914. this.spriteCellChangeSpeed = 0;
  50915. /**
  50916. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50917. */
  50918. this.startSpriteCellID = 0;
  50919. /**
  50920. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50921. */
  50922. this.endSpriteCellID = 0;
  50923. /**
  50924. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50925. */
  50926. this.spriteCellWidth = 0;
  50927. /**
  50928. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50929. */
  50930. this.spriteCellHeight = 0;
  50931. /**
  50932. * An event triggered when the system is disposed.
  50933. */
  50934. this.onDisposeObservable = new BABYLON.Observable();
  50935. this._particles = new Array();
  50936. this._stockParticles = new Array();
  50937. this._newPartsExcess = 0;
  50938. this._vertexBuffers = {};
  50939. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50940. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50941. this._scaledDirection = BABYLON.Vector3.Zero();
  50942. this._scaledGravity = BABYLON.Vector3.Zero();
  50943. this._currentRenderId = -1;
  50944. this._started = false;
  50945. this._stopped = false;
  50946. this._actualFrame = 0;
  50947. this._vertexBufferSize = 11;
  50948. // start of sub system methods
  50949. /**
  50950. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50951. * Its lifetime will start back at 0.
  50952. */
  50953. this.recycleParticle = function (particle) {
  50954. var lastParticle = _this._particles.pop();
  50955. if (lastParticle !== particle) {
  50956. lastParticle.copyTo(particle);
  50957. }
  50958. _this._stockParticles.push(lastParticle);
  50959. };
  50960. this._createParticle = function () {
  50961. var particle;
  50962. if (_this._stockParticles.length !== 0) {
  50963. particle = _this._stockParticles.pop();
  50964. particle.age = 0;
  50965. particle.cellIndex = _this.startSpriteCellID;
  50966. }
  50967. else {
  50968. particle = new BABYLON.Particle(_this);
  50969. }
  50970. return particle;
  50971. };
  50972. this._emitFromParticle = function (particle) {
  50973. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  50974. return;
  50975. }
  50976. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  50977. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  50978. subSystem._rootParticleSystem = _this;
  50979. _this.activeSubSystems.push(subSystem);
  50980. subSystem.start();
  50981. };
  50982. this._appendParticleVertexes = null;
  50983. this.id = name;
  50984. this.name = name;
  50985. this._capacity = capacity;
  50986. this._epsilon = epsilon;
  50987. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50988. if (isAnimationSheetEnabled) {
  50989. this._vertexBufferSize = 12;
  50990. }
  50991. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50992. this._customEffect = customEffect;
  50993. scene.particleSystems.push(this);
  50994. this._createIndexBuffer();
  50995. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50996. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50997. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50998. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50999. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51000. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51001. if (this._isAnimationSheetEnabled) {
  51002. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51003. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51004. }
  51005. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51006. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51007. this._vertexBuffers["options"] = options;
  51008. // Default emitter type
  51009. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51010. this.updateFunction = function (particles) {
  51011. for (var index = 0; index < particles.length; index++) {
  51012. var particle = particles[index];
  51013. particle.age += _this._scaledUpdateSpeed;
  51014. if (particle.age >= particle.lifeTime) {
  51015. _this._emitFromParticle(particle);
  51016. _this.recycleParticle(particle);
  51017. index--;
  51018. continue;
  51019. }
  51020. else {
  51021. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51022. particle.color.addInPlace(_this._scaledColorStep);
  51023. if (particle.color.a < 0)
  51024. particle.color.a = 0;
  51025. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51026. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51027. particle.position.addInPlace(_this._scaledDirection);
  51028. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51029. particle.direction.addInPlace(_this._scaledGravity);
  51030. if (_this._isAnimationSheetEnabled) {
  51031. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51032. }
  51033. }
  51034. }
  51035. };
  51036. }
  51037. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51038. /**
  51039. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51040. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51041. */
  51042. get: function () {
  51043. if (this.particleEmitterType.direction1) {
  51044. return this.particleEmitterType.direction1;
  51045. }
  51046. return BABYLON.Vector3.Zero();
  51047. },
  51048. set: function (value) {
  51049. if (this.particleEmitterType.direction1) {
  51050. this.particleEmitterType.direction1 = value;
  51051. }
  51052. },
  51053. enumerable: true,
  51054. configurable: true
  51055. });
  51056. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51057. /**
  51058. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51059. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51060. */
  51061. get: function () {
  51062. if (this.particleEmitterType.direction2) {
  51063. return this.particleEmitterType.direction2;
  51064. }
  51065. return BABYLON.Vector3.Zero();
  51066. },
  51067. set: function (value) {
  51068. if (this.particleEmitterType.direction2) {
  51069. this.particleEmitterType.direction2 = value;
  51070. }
  51071. },
  51072. enumerable: true,
  51073. configurable: true
  51074. });
  51075. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51076. /**
  51077. * 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.
  51078. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51079. */
  51080. get: function () {
  51081. if (this.particleEmitterType.minEmitBox) {
  51082. return this.particleEmitterType.minEmitBox;
  51083. }
  51084. return BABYLON.Vector3.Zero();
  51085. },
  51086. set: function (value) {
  51087. if (this.particleEmitterType.minEmitBox) {
  51088. this.particleEmitterType.minEmitBox = value;
  51089. }
  51090. },
  51091. enumerable: true,
  51092. configurable: true
  51093. });
  51094. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51095. /**
  51096. * 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.
  51097. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51098. */
  51099. get: function () {
  51100. if (this.particleEmitterType.maxEmitBox) {
  51101. return this.particleEmitterType.maxEmitBox;
  51102. }
  51103. return BABYLON.Vector3.Zero();
  51104. },
  51105. set: function (value) {
  51106. if (this.particleEmitterType.maxEmitBox) {
  51107. this.particleEmitterType.maxEmitBox = value;
  51108. }
  51109. },
  51110. enumerable: true,
  51111. configurable: true
  51112. });
  51113. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51114. /**
  51115. * Sets a callback that will be triggered when the system is disposed.
  51116. */
  51117. set: function (callback) {
  51118. if (this._onDisposeObserver) {
  51119. this.onDisposeObservable.remove(this._onDisposeObserver);
  51120. }
  51121. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51122. },
  51123. enumerable: true,
  51124. configurable: true
  51125. });
  51126. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51127. /**
  51128. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51129. */
  51130. get: function () {
  51131. return this._isAnimationSheetEnabled;
  51132. },
  51133. enumerable: true,
  51134. configurable: true
  51135. });
  51136. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51137. //end of Sub-emitter
  51138. /**
  51139. * Gets the current list of active particles
  51140. */
  51141. get: function () {
  51142. return this._particles;
  51143. },
  51144. enumerable: true,
  51145. configurable: true
  51146. });
  51147. /**
  51148. * Returns the string "ParticleSystem"
  51149. * @returns a string containing the class name
  51150. */
  51151. ParticleSystem.prototype.getClassName = function () {
  51152. return "ParticleSystem";
  51153. };
  51154. ParticleSystem.prototype._createIndexBuffer = function () {
  51155. var indices = [];
  51156. var index = 0;
  51157. for (var count = 0; count < this._capacity; count++) {
  51158. indices.push(index);
  51159. indices.push(index + 1);
  51160. indices.push(index + 2);
  51161. indices.push(index);
  51162. indices.push(index + 2);
  51163. indices.push(index + 3);
  51164. index += 4;
  51165. }
  51166. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51167. };
  51168. /**
  51169. * Gets the maximum number of particles active at the same time.
  51170. * @returns The max number of active particles.
  51171. */
  51172. ParticleSystem.prototype.getCapacity = function () {
  51173. return this._capacity;
  51174. };
  51175. /**
  51176. * Gets Wether there are still active particles in the system.
  51177. * @returns True if it is alive, otherwise false.
  51178. */
  51179. ParticleSystem.prototype.isAlive = function () {
  51180. return this._alive;
  51181. };
  51182. /**
  51183. * Gets Wether the system has been started.
  51184. * @returns True if it has been started, otherwise false.
  51185. */
  51186. ParticleSystem.prototype.isStarted = function () {
  51187. return this._started;
  51188. };
  51189. /**
  51190. * Starts the particle system and begins to emit.
  51191. */
  51192. ParticleSystem.prototype.start = function () {
  51193. this._started = true;
  51194. this._stopped = false;
  51195. this._actualFrame = 0;
  51196. if (this.subEmitters && this.subEmitters.length != 0) {
  51197. this.activeSubSystems = new Array();
  51198. }
  51199. };
  51200. /**
  51201. * Stops the particle system.
  51202. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51203. */
  51204. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51205. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51206. this._stopped = true;
  51207. if (stopSubEmitters) {
  51208. this._stopSubEmitters();
  51209. }
  51210. };
  51211. // animation sheet
  51212. /**
  51213. * Remove all active particles
  51214. */
  51215. ParticleSystem.prototype.reset = function () {
  51216. this._stockParticles = [];
  51217. this._particles = [];
  51218. };
  51219. /**
  51220. * @ignore (for internal use only)
  51221. */
  51222. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51223. var offset = index * this._vertexBufferSize;
  51224. this._vertexData[offset] = particle.position.x;
  51225. this._vertexData[offset + 1] = particle.position.y;
  51226. this._vertexData[offset + 2] = particle.position.z;
  51227. this._vertexData[offset + 3] = particle.color.r;
  51228. this._vertexData[offset + 4] = particle.color.g;
  51229. this._vertexData[offset + 5] = particle.color.b;
  51230. this._vertexData[offset + 6] = particle.color.a;
  51231. this._vertexData[offset + 7] = particle.angle;
  51232. this._vertexData[offset + 8] = particle.size;
  51233. this._vertexData[offset + 9] = offsetX;
  51234. this._vertexData[offset + 10] = offsetY;
  51235. };
  51236. /**
  51237. * @ignore (for internal use only)
  51238. */
  51239. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51240. if (offsetX === 0)
  51241. offsetX = this._epsilon;
  51242. else if (offsetX === 1)
  51243. offsetX = 1 - this._epsilon;
  51244. if (offsetY === 0)
  51245. offsetY = this._epsilon;
  51246. else if (offsetY === 1)
  51247. offsetY = 1 - this._epsilon;
  51248. var offset = index * this._vertexBufferSize;
  51249. this._vertexData[offset] = particle.position.x;
  51250. this._vertexData[offset + 1] = particle.position.y;
  51251. this._vertexData[offset + 2] = particle.position.z;
  51252. this._vertexData[offset + 3] = particle.color.r;
  51253. this._vertexData[offset + 4] = particle.color.g;
  51254. this._vertexData[offset + 5] = particle.color.b;
  51255. this._vertexData[offset + 6] = particle.color.a;
  51256. this._vertexData[offset + 7] = particle.angle;
  51257. this._vertexData[offset + 8] = particle.size;
  51258. this._vertexData[offset + 9] = offsetX;
  51259. this._vertexData[offset + 10] = offsetY;
  51260. this._vertexData[offset + 11] = particle.cellIndex;
  51261. };
  51262. ParticleSystem.prototype._stopSubEmitters = function () {
  51263. if (!this.activeSubSystems) {
  51264. return;
  51265. }
  51266. this.activeSubSystems.forEach(function (subSystem) {
  51267. subSystem.stop(true);
  51268. });
  51269. this.activeSubSystems = new Array();
  51270. };
  51271. ParticleSystem.prototype._removeFromRoot = function () {
  51272. if (!this._rootParticleSystem) {
  51273. return;
  51274. }
  51275. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51276. if (index !== -1) {
  51277. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51278. }
  51279. };
  51280. // end of sub system methods
  51281. ParticleSystem.prototype._update = function (newParticles) {
  51282. // Update current
  51283. this._alive = this._particles.length > 0;
  51284. this.updateFunction(this._particles);
  51285. // Add new ones
  51286. var worldMatrix;
  51287. if (this.emitter.position) {
  51288. var emitterMesh = this.emitter;
  51289. worldMatrix = emitterMesh.getWorldMatrix();
  51290. }
  51291. else {
  51292. var emitterPosition = this.emitter;
  51293. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51294. }
  51295. var particle;
  51296. for (var index = 0; index < newParticles; index++) {
  51297. if (this._particles.length === this._capacity) {
  51298. break;
  51299. }
  51300. particle = this._createParticle();
  51301. this._particles.push(particle);
  51302. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51303. if (this.startPositionFunction) {
  51304. this.startPositionFunction(worldMatrix, particle.position, particle);
  51305. }
  51306. else {
  51307. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51308. }
  51309. if (this.startDirectionFunction) {
  51310. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51311. }
  51312. else {
  51313. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51314. }
  51315. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51316. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51317. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51318. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51319. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51320. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51321. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51322. }
  51323. };
  51324. ParticleSystem.prototype._getEffect = function () {
  51325. if (this._customEffect) {
  51326. return this._customEffect;
  51327. }
  51328. ;
  51329. var defines = [];
  51330. if (this._scene.clipPlane) {
  51331. defines.push("#define CLIPPLANE");
  51332. }
  51333. if (this._isAnimationSheetEnabled) {
  51334. defines.push("#define ANIMATESHEET");
  51335. }
  51336. // Effect
  51337. var join = defines.join("\n");
  51338. if (this._cachedDefines !== join) {
  51339. this._cachedDefines = join;
  51340. var attributesNamesOrOptions;
  51341. var effectCreationOption;
  51342. if (this._isAnimationSheetEnabled) {
  51343. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51344. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51345. }
  51346. else {
  51347. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51348. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51349. }
  51350. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51351. }
  51352. return this._effect;
  51353. };
  51354. /**
  51355. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51356. */
  51357. ParticleSystem.prototype.animate = function () {
  51358. if (!this._started)
  51359. return;
  51360. var effect = this._getEffect();
  51361. // Check
  51362. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51363. return;
  51364. if (this._currentRenderId === this._scene.getRenderId()) {
  51365. return;
  51366. }
  51367. this._currentRenderId = this._scene.getRenderId();
  51368. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51369. // determine the number of particles we need to create
  51370. var newParticles;
  51371. if (this.manualEmitCount > -1) {
  51372. newParticles = this.manualEmitCount;
  51373. this._newPartsExcess = 0;
  51374. this.manualEmitCount = 0;
  51375. }
  51376. else {
  51377. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51378. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51379. }
  51380. if (this._newPartsExcess > 1.0) {
  51381. newParticles += this._newPartsExcess >> 0;
  51382. this._newPartsExcess -= this._newPartsExcess >> 0;
  51383. }
  51384. this._alive = false;
  51385. if (!this._stopped) {
  51386. this._actualFrame += this._scaledUpdateSpeed;
  51387. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51388. this.stop();
  51389. }
  51390. else {
  51391. newParticles = 0;
  51392. }
  51393. this._update(newParticles);
  51394. // Stopped?
  51395. if (this._stopped) {
  51396. if (!this._alive) {
  51397. this._started = false;
  51398. if (this.onAnimationEnd) {
  51399. this.onAnimationEnd();
  51400. }
  51401. if (this.disposeOnStop) {
  51402. this._scene._toBeDisposed.push(this);
  51403. }
  51404. }
  51405. }
  51406. // Animation sheet
  51407. if (this._isAnimationSheetEnabled) {
  51408. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51409. }
  51410. else {
  51411. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51412. }
  51413. // Update VBO
  51414. var offset = 0;
  51415. for (var index = 0; index < this._particles.length; index++) {
  51416. var particle = this._particles[index];
  51417. this._appendParticleVertexes(offset, particle);
  51418. offset += 4;
  51419. }
  51420. if (this._vertexBuffer) {
  51421. this._vertexBuffer.update(this._vertexData);
  51422. }
  51423. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51424. this.stop();
  51425. }
  51426. };
  51427. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51428. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51429. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51430. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51431. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51432. };
  51433. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51434. this._appendParticleVertex(offset++, particle, 0, 0);
  51435. this._appendParticleVertex(offset++, particle, 1, 0);
  51436. this._appendParticleVertex(offset++, particle, 1, 1);
  51437. this._appendParticleVertex(offset++, particle, 0, 1);
  51438. };
  51439. /**
  51440. * Rebuilds the particle system.
  51441. */
  51442. ParticleSystem.prototype.rebuild = function () {
  51443. this._createIndexBuffer();
  51444. if (this._vertexBuffer) {
  51445. this._vertexBuffer._rebuild();
  51446. }
  51447. };
  51448. /**
  51449. * Is this system ready to be used/rendered
  51450. * @return true if the system is ready
  51451. */
  51452. ParticleSystem.prototype.isReady = function () {
  51453. var effect = this._getEffect();
  51454. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51455. return false;
  51456. }
  51457. return true;
  51458. };
  51459. /**
  51460. * Renders the particle system in its current state.
  51461. * @returns the current number of particles
  51462. */
  51463. ParticleSystem.prototype.render = function () {
  51464. var effect = this._getEffect();
  51465. // Check
  51466. if (!this.isReady() || !this._particles.length) {
  51467. return 0;
  51468. }
  51469. var engine = this._scene.getEngine();
  51470. // Render
  51471. engine.enableEffect(effect);
  51472. engine.setState(false);
  51473. var viewMatrix = this._scene.getViewMatrix();
  51474. effect.setTexture("diffuseSampler", this.particleTexture);
  51475. effect.setMatrix("view", viewMatrix);
  51476. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51477. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51478. var baseSize = this.particleTexture.getBaseSize();
  51479. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51480. }
  51481. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51482. if (this._scene.clipPlane) {
  51483. var clipPlane = this._scene.clipPlane;
  51484. var invView = viewMatrix.clone();
  51485. invView.invert();
  51486. effect.setMatrix("invView", invView);
  51487. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51488. }
  51489. // VBOs
  51490. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51491. // Draw order
  51492. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51493. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51494. }
  51495. else {
  51496. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51497. }
  51498. if (this.forceDepthWrite) {
  51499. engine.setDepthWrite(true);
  51500. }
  51501. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51502. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51503. return this._particles.length;
  51504. };
  51505. /**
  51506. * Disposes the particle system and free the associated resources
  51507. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51508. */
  51509. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51510. if (disposeTexture === void 0) { disposeTexture = true; }
  51511. if (this._vertexBuffer) {
  51512. this._vertexBuffer.dispose();
  51513. this._vertexBuffer = null;
  51514. }
  51515. if (this._indexBuffer) {
  51516. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51517. this._indexBuffer = null;
  51518. }
  51519. if (disposeTexture && this.particleTexture) {
  51520. this.particleTexture.dispose();
  51521. this.particleTexture = null;
  51522. }
  51523. this._removeFromRoot();
  51524. // Remove from scene
  51525. var index = this._scene.particleSystems.indexOf(this);
  51526. if (index > -1) {
  51527. this._scene.particleSystems.splice(index, 1);
  51528. }
  51529. // Callback
  51530. this.onDisposeObservable.notifyObservers(this);
  51531. this.onDisposeObservable.clear();
  51532. };
  51533. /**
  51534. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51535. * @param radius The radius of the sphere to emit from
  51536. * @returns the emitter
  51537. */
  51538. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51539. if (radius === void 0) { radius = 1; }
  51540. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51541. this.particleEmitterType = particleEmitter;
  51542. return particleEmitter;
  51543. };
  51544. /**
  51545. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51546. * @param radius The radius of the sphere to emit from
  51547. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51548. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51549. * @returns the emitter
  51550. */
  51551. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51552. if (radius === void 0) { radius = 1; }
  51553. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51554. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51555. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51556. this.particleEmitterType = particleEmitter;
  51557. return particleEmitter;
  51558. };
  51559. /**
  51560. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51561. * @param radius The radius of the cone to emit from
  51562. * @param angle The base angle of the cone
  51563. * @returns the emitter
  51564. */
  51565. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51566. if (radius === void 0) { radius = 1; }
  51567. if (angle === void 0) { angle = Math.PI / 4; }
  51568. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51569. this.particleEmitterType = particleEmitter;
  51570. return particleEmitter;
  51571. };
  51572. // 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.
  51573. /**
  51574. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51575. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51576. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51577. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51578. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51579. * @returns the emitter
  51580. */
  51581. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51582. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51583. this.direction1 = direction1;
  51584. this.direction2 = direction2;
  51585. this.minEmitBox = minEmitBox;
  51586. this.maxEmitBox = maxEmitBox;
  51587. this.particleEmitterType = particleEmitter;
  51588. return particleEmitter;
  51589. };
  51590. // Clone
  51591. /**
  51592. * Clones the particle system.
  51593. * @param name The name of the cloned object
  51594. * @param newEmitter The new emitter to use
  51595. * @returns the cloned particle system
  51596. */
  51597. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51598. var custom = null;
  51599. var program = null;
  51600. if (this.customShader != null) {
  51601. program = this.customShader;
  51602. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51603. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51604. }
  51605. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51606. result.customShader = program;
  51607. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51608. if (newEmitter === undefined) {
  51609. newEmitter = this.emitter;
  51610. }
  51611. result.emitter = newEmitter;
  51612. if (this.particleTexture) {
  51613. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51614. }
  51615. if (!this.preventAutoStart) {
  51616. result.start();
  51617. }
  51618. return result;
  51619. };
  51620. /**
  51621. * Serializes the particle system to a JSON object.
  51622. * @returns the JSON object
  51623. */
  51624. ParticleSystem.prototype.serialize = function () {
  51625. var serializationObject = {};
  51626. serializationObject.name = this.name;
  51627. serializationObject.id = this.id;
  51628. // Emitter
  51629. if (this.emitter.position) {
  51630. var emitterMesh = this.emitter;
  51631. serializationObject.emitterId = emitterMesh.id;
  51632. }
  51633. else {
  51634. var emitterPosition = this.emitter;
  51635. serializationObject.emitter = emitterPosition.asArray();
  51636. }
  51637. serializationObject.capacity = this.getCapacity();
  51638. if (this.particleTexture) {
  51639. serializationObject.textureName = this.particleTexture.name;
  51640. }
  51641. // Animations
  51642. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51643. // Particle system
  51644. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51645. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51646. serializationObject.minSize = this.minSize;
  51647. serializationObject.maxSize = this.maxSize;
  51648. serializationObject.minEmitPower = this.minEmitPower;
  51649. serializationObject.maxEmitPower = this.maxEmitPower;
  51650. serializationObject.minLifeTime = this.minLifeTime;
  51651. serializationObject.maxLifeTime = this.maxLifeTime;
  51652. serializationObject.emitRate = this.emitRate;
  51653. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51654. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51655. serializationObject.gravity = this.gravity.asArray();
  51656. serializationObject.direction1 = this.direction1.asArray();
  51657. serializationObject.direction2 = this.direction2.asArray();
  51658. serializationObject.color1 = this.color1.asArray();
  51659. serializationObject.color2 = this.color2.asArray();
  51660. serializationObject.colorDead = this.colorDead.asArray();
  51661. serializationObject.updateSpeed = this.updateSpeed;
  51662. serializationObject.targetStopDuration = this.targetStopDuration;
  51663. serializationObject.textureMask = this.textureMask.asArray();
  51664. serializationObject.blendMode = this.blendMode;
  51665. serializationObject.customShader = this.customShader;
  51666. serializationObject.preventAutoStart = this.preventAutoStart;
  51667. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51668. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51669. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51670. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51671. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51672. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51673. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51674. // Emitter
  51675. if (this.particleEmitterType) {
  51676. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51677. }
  51678. return serializationObject;
  51679. };
  51680. /**
  51681. * Parses a JSON object to create a particle system.
  51682. * @param parsedParticleSystem The JSON object to parse
  51683. * @param scene The scene to create the particle system in
  51684. * @param rootUrl The root url to use to load external dependencies like texture
  51685. * @returns the Parsed particle system
  51686. */
  51687. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51688. var name = parsedParticleSystem.name;
  51689. var custom = null;
  51690. var program = null;
  51691. if (parsedParticleSystem.customShader) {
  51692. program = parsedParticleSystem.customShader;
  51693. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51694. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51695. }
  51696. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51697. particleSystem.customShader = program;
  51698. if (parsedParticleSystem.id) {
  51699. particleSystem.id = parsedParticleSystem.id;
  51700. }
  51701. // Auto start
  51702. if (parsedParticleSystem.preventAutoStart) {
  51703. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51704. }
  51705. // Texture
  51706. if (parsedParticleSystem.textureName) {
  51707. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51708. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51709. }
  51710. // Emitter
  51711. if (parsedParticleSystem.emitterId) {
  51712. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51713. }
  51714. else {
  51715. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51716. }
  51717. // Animations
  51718. if (parsedParticleSystem.animations) {
  51719. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51720. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51721. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51722. }
  51723. }
  51724. if (parsedParticleSystem.autoAnimate) {
  51725. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51726. }
  51727. // Particle system
  51728. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51729. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51730. particleSystem.minSize = parsedParticleSystem.minSize;
  51731. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51732. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51733. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51734. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51735. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51736. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51737. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51738. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51739. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51740. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51741. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51742. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51743. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51744. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51745. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51746. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51747. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51748. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51749. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51750. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51751. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51752. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51753. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51754. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51755. if (!particleSystem.preventAutoStart) {
  51756. particleSystem.start();
  51757. }
  51758. return particleSystem;
  51759. };
  51760. /**
  51761. * Source color is added to the destination color without alpha affecting the result.
  51762. */
  51763. ParticleSystem.BLENDMODE_ONEONE = 0;
  51764. /**
  51765. * Blend current color and particle color using particle’s alpha.
  51766. */
  51767. ParticleSystem.BLENDMODE_STANDARD = 1;
  51768. return ParticleSystem;
  51769. }());
  51770. BABYLON.ParticleSystem = ParticleSystem;
  51771. })(BABYLON || (BABYLON = {}));
  51772. //# sourceMappingURL=babylon.particleSystem.js.map
  51773. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51774. var BABYLON;
  51775. (function (BABYLON) {
  51776. /**
  51777. * Particle emitter emitting particles from the inside of a box.
  51778. * It emits the particles randomly between 2 given directions.
  51779. */
  51780. var BoxParticleEmitter = /** @class */ (function () {
  51781. /**
  51782. * Creates a new instance of @see BoxParticleEmitter
  51783. */
  51784. function BoxParticleEmitter() {
  51785. /**
  51786. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51787. */
  51788. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51789. /**
  51790. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51791. */
  51792. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51793. /**
  51794. * 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.
  51795. */
  51796. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51797. /**
  51798. * 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.
  51799. */
  51800. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51801. }
  51802. /**
  51803. * Called by the particle System when the direction is computed for the created particle.
  51804. * @param emitPower is the power of the particle (speed)
  51805. * @param worldMatrix is the world matrix of the particle system
  51806. * @param directionToUpdate is the direction vector to update with the result
  51807. * @param particle is the particle we are computed the direction for
  51808. */
  51809. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51810. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51811. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51812. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51813. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51814. };
  51815. /**
  51816. * Called by the particle System when the position is computed for the created particle.
  51817. * @param worldMatrix is the world matrix of the particle system
  51818. * @param positionToUpdate is the position vector to update with the result
  51819. * @param particle is the particle we are computed the position for
  51820. */
  51821. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51822. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51823. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51824. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51825. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51826. };
  51827. /**
  51828. * Clones the current emitter and returns a copy of it
  51829. * @returns the new emitter
  51830. */
  51831. BoxParticleEmitter.prototype.clone = function () {
  51832. var newOne = new BoxParticleEmitter();
  51833. BABYLON.Tools.DeepCopy(this, newOne);
  51834. return newOne;
  51835. };
  51836. /**
  51837. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51838. * @param effect defines the update shader
  51839. */
  51840. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51841. effect.setVector3("direction1", this.direction1);
  51842. effect.setVector3("direction2", this.direction2);
  51843. effect.setVector3("minEmitBox", this.minEmitBox);
  51844. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51845. };
  51846. /**
  51847. * Returns a string to use to update the GPU particles update shader
  51848. * @returns a string containng the defines string
  51849. */
  51850. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51851. return "#define BOXEMITTER";
  51852. };
  51853. /**
  51854. * Returns the string "BoxEmitter"
  51855. * @returns a string containing the class name
  51856. */
  51857. BoxParticleEmitter.prototype.getClassName = function () {
  51858. return "BoxEmitter";
  51859. };
  51860. /**
  51861. * Serializes the particle system to a JSON object.
  51862. * @returns the JSON object
  51863. */
  51864. BoxParticleEmitter.prototype.serialize = function () {
  51865. var serializationObject = {};
  51866. serializationObject.type = this.getClassName();
  51867. serializationObject.direction1 = this.direction1.asArray();
  51868. ;
  51869. serializationObject.direction2 = this.direction2.asArray();
  51870. ;
  51871. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51872. ;
  51873. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51874. ;
  51875. return serializationObject;
  51876. };
  51877. /**
  51878. * Parse properties from a JSON object
  51879. * @param serializationObject defines the JSON object
  51880. */
  51881. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51882. this.direction1.copyFrom(serializationObject.direction1);
  51883. this.direction2.copyFrom(serializationObject.direction2);
  51884. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51885. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51886. };
  51887. return BoxParticleEmitter;
  51888. }());
  51889. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51890. })(BABYLON || (BABYLON = {}));
  51891. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51892. var BABYLON;
  51893. (function (BABYLON) {
  51894. /**
  51895. * Particle emitter emitting particles from the inside of a cone.
  51896. * It emits the particles alongside the cone volume from the base to the particle.
  51897. * The emission direction might be randomized.
  51898. */
  51899. var ConeParticleEmitter = /** @class */ (function () {
  51900. /**
  51901. * Creates a new instance of @see ConeParticleEmitter
  51902. * @param radius the radius of the emission cone (1 by default)
  51903. * @param angles the cone base angle (PI by default)
  51904. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51905. */
  51906. function ConeParticleEmitter(radius,
  51907. /**
  51908. * The radius of the emission cone.
  51909. */
  51910. angle,
  51911. /**
  51912. * The cone base angle.
  51913. */
  51914. directionRandomizer) {
  51915. if (radius === void 0) { radius = 1; }
  51916. if (angle === void 0) { angle = Math.PI; }
  51917. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51918. this.angle = angle;
  51919. this.directionRandomizer = directionRandomizer;
  51920. this.radius = radius;
  51921. }
  51922. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51923. /**
  51924. * Gets the radius of the emission cone.
  51925. */
  51926. get: function () {
  51927. return this._radius;
  51928. },
  51929. /**
  51930. * Sets the radius of the emission cone.
  51931. */
  51932. set: function (value) {
  51933. this._radius = value;
  51934. if (this.angle !== 0) {
  51935. this._height = value / Math.tan(this.angle / 2);
  51936. }
  51937. else {
  51938. this._height = 1;
  51939. }
  51940. },
  51941. enumerable: true,
  51942. configurable: true
  51943. });
  51944. /**
  51945. * Called by the particle System when the direction is computed for the created particle.
  51946. * @param emitPower is the power of the particle (speed)
  51947. * @param worldMatrix is the world matrix of the particle system
  51948. * @param directionToUpdate is the direction vector to update with the result
  51949. * @param particle is the particle we are computed the direction for
  51950. */
  51951. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51952. if (this.angle === 0) {
  51953. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51954. }
  51955. else {
  51956. // measure the direction Vector from the emitter to the particle.
  51957. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51958. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51959. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51960. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51961. direction.x += randX;
  51962. direction.y += randY;
  51963. direction.z += randZ;
  51964. direction.normalize();
  51965. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51966. }
  51967. };
  51968. /**
  51969. * Called by the particle System when the position is computed for the created particle.
  51970. * @param worldMatrix is the world matrix of the particle system
  51971. * @param positionToUpdate is the position vector to update with the result
  51972. * @param particle is the particle we are computed the position for
  51973. */
  51974. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51975. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51976. var h = BABYLON.Scalar.RandomRange(0, 1);
  51977. // Better distribution in a cone at normal angles.
  51978. h = 1 - h * h;
  51979. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51980. radius = radius * h / this._height;
  51981. var randX = radius * Math.sin(s);
  51982. var randZ = radius * Math.cos(s);
  51983. var randY = h * this._height;
  51984. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51985. };
  51986. /**
  51987. * Clones the current emitter and returns a copy of it
  51988. * @returns the new emitter
  51989. */
  51990. ConeParticleEmitter.prototype.clone = function () {
  51991. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51992. BABYLON.Tools.DeepCopy(this, newOne);
  51993. return newOne;
  51994. };
  51995. /**
  51996. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51997. * @param effect defines the update shader
  51998. */
  51999. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52000. effect.setFloat("radius", this.radius);
  52001. effect.setFloat("angle", this.angle);
  52002. effect.setFloat("height", this._height);
  52003. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52004. };
  52005. /**
  52006. * Returns a string to use to update the GPU particles update shader
  52007. * @returns a string containng the defines string
  52008. */
  52009. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52010. return "#define CONEEMITTER";
  52011. };
  52012. /**
  52013. * Returns the string "BoxEmitter"
  52014. * @returns a string containing the class name
  52015. */
  52016. ConeParticleEmitter.prototype.getClassName = function () {
  52017. return "ConeEmitter";
  52018. };
  52019. /**
  52020. * Serializes the particle system to a JSON object.
  52021. * @returns the JSON object
  52022. */
  52023. ConeParticleEmitter.prototype.serialize = function () {
  52024. var serializationObject = {};
  52025. serializationObject.type = this.getClassName();
  52026. serializationObject.radius = this.radius;
  52027. serializationObject.angle = this.angle;
  52028. serializationObject.directionRandomizer = this.directionRandomizer;
  52029. return serializationObject;
  52030. };
  52031. /**
  52032. * Parse properties from a JSON object
  52033. * @param serializationObject defines the JSON object
  52034. */
  52035. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52036. this.radius = serializationObject.radius;
  52037. this.angle = serializationObject.angle;
  52038. this.directionRandomizer = serializationObject.directionRandomizer;
  52039. };
  52040. return ConeParticleEmitter;
  52041. }());
  52042. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52043. })(BABYLON || (BABYLON = {}));
  52044. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52045. var BABYLON;
  52046. (function (BABYLON) {
  52047. /**
  52048. * Particle emitter emitting particles from the inside of a sphere.
  52049. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52050. */
  52051. var SphereParticleEmitter = /** @class */ (function () {
  52052. /**
  52053. * Creates a new instance of @see SphereParticleEmitter
  52054. * @param radius the radius of the emission sphere (1 by default)
  52055. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52056. */
  52057. function SphereParticleEmitter(
  52058. /**
  52059. * The radius of the emission sphere.
  52060. */
  52061. radius,
  52062. /**
  52063. * How much to randomize the particle direction [0-1].
  52064. */
  52065. directionRandomizer) {
  52066. if (radius === void 0) { radius = 1; }
  52067. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52068. this.radius = radius;
  52069. this.directionRandomizer = directionRandomizer;
  52070. }
  52071. /**
  52072. * Called by the particle System when the direction is computed for the created particle.
  52073. * @param emitPower is the power of the particle (speed)
  52074. * @param worldMatrix is the world matrix of the particle system
  52075. * @param directionToUpdate is the direction vector to update with the result
  52076. * @param particle is the particle we are computed the direction for
  52077. */
  52078. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52079. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52080. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52081. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52082. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52083. direction.x += randX;
  52084. direction.y += randY;
  52085. direction.z += randZ;
  52086. direction.normalize();
  52087. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52088. };
  52089. /**
  52090. * Called by the particle System when the position is computed for the created particle.
  52091. * @param worldMatrix is the world matrix of the particle system
  52092. * @param positionToUpdate is the position vector to update with the result
  52093. * @param particle is the particle we are computed the position for
  52094. */
  52095. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52096. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52097. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52098. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52099. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52100. var randY = randRadius * Math.cos(theta);
  52101. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52102. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52103. };
  52104. /**
  52105. * Clones the current emitter and returns a copy of it
  52106. * @returns the new emitter
  52107. */
  52108. SphereParticleEmitter.prototype.clone = function () {
  52109. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52110. BABYLON.Tools.DeepCopy(this, newOne);
  52111. return newOne;
  52112. };
  52113. /**
  52114. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52115. * @param effect defines the update shader
  52116. */
  52117. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52118. effect.setFloat("radius", this.radius);
  52119. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52120. };
  52121. /**
  52122. * Returns a string to use to update the GPU particles update shader
  52123. * @returns a string containng the defines string
  52124. */
  52125. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52126. return "#define SPHEREEMITTER";
  52127. };
  52128. /**
  52129. * Returns the string "SphereParticleEmitter"
  52130. * @returns a string containing the class name
  52131. */
  52132. SphereParticleEmitter.prototype.getClassName = function () {
  52133. return "SphereParticleEmitter";
  52134. };
  52135. /**
  52136. * Serializes the particle system to a JSON object.
  52137. * @returns the JSON object
  52138. */
  52139. SphereParticleEmitter.prototype.serialize = function () {
  52140. var serializationObject = {};
  52141. serializationObject.type = this.getClassName();
  52142. serializationObject.radius = this.radius;
  52143. serializationObject.directionRandomizer = this.directionRandomizer;
  52144. return serializationObject;
  52145. };
  52146. /**
  52147. * Parse properties from a JSON object
  52148. * @param serializationObject defines the JSON object
  52149. */
  52150. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52151. this.radius = serializationObject.radius;
  52152. this.directionRandomizer = serializationObject.directionRandomizer;
  52153. };
  52154. return SphereParticleEmitter;
  52155. }());
  52156. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52157. /**
  52158. * Particle emitter emitting particles from the inside of a sphere.
  52159. * It emits the particles randomly between two vectors.
  52160. */
  52161. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52162. __extends(SphereDirectedParticleEmitter, _super);
  52163. /**
  52164. * Creates a new instance of @see SphereDirectedParticleEmitter
  52165. * @param radius the radius of the emission sphere (1 by default)
  52166. * @param direction1 the min limit of the emission direction (up vector by default)
  52167. * @param direction2 the max limit of the emission direction (up vector by default)
  52168. */
  52169. function SphereDirectedParticleEmitter(radius,
  52170. /**
  52171. * The min limit of the emission direction.
  52172. */
  52173. direction1,
  52174. /**
  52175. * The max limit of the emission direction.
  52176. */
  52177. direction2) {
  52178. if (radius === void 0) { radius = 1; }
  52179. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52180. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52181. var _this = _super.call(this, radius) || this;
  52182. _this.direction1 = direction1;
  52183. _this.direction2 = direction2;
  52184. return _this;
  52185. }
  52186. /**
  52187. * Called by the particle System when the direction is computed for the created particle.
  52188. * @param emitPower is the power of the particle (speed)
  52189. * @param worldMatrix is the world matrix of the particle system
  52190. * @param directionToUpdate is the direction vector to update with the result
  52191. * @param particle is the particle we are computed the direction for
  52192. */
  52193. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52194. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52195. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52196. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52197. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52198. };
  52199. /**
  52200. * Clones the current emitter and returns a copy of it
  52201. * @returns the new emitter
  52202. */
  52203. SphereDirectedParticleEmitter.prototype.clone = function () {
  52204. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52205. BABYLON.Tools.DeepCopy(this, newOne);
  52206. return newOne;
  52207. };
  52208. /**
  52209. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52210. * @param effect defines the update shader
  52211. */
  52212. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52213. effect.setFloat("radius", this.radius);
  52214. effect.setVector3("direction1", this.direction1);
  52215. effect.setVector3("direction2", this.direction2);
  52216. };
  52217. /**
  52218. * Returns a string to use to update the GPU particles update shader
  52219. * @returns a string containng the defines string
  52220. */
  52221. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52222. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52223. };
  52224. /**
  52225. * Returns the string "SphereDirectedParticleEmitter"
  52226. * @returns a string containing the class name
  52227. */
  52228. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52229. return "SphereDirectedParticleEmitter";
  52230. };
  52231. /**
  52232. * Serializes the particle system to a JSON object.
  52233. * @returns the JSON object
  52234. */
  52235. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52236. var serializationObject = _super.prototype.serialize.call(this);
  52237. ;
  52238. serializationObject.direction1 = this.direction1.asArray();
  52239. ;
  52240. serializationObject.direction2 = this.direction2.asArray();
  52241. ;
  52242. return serializationObject;
  52243. };
  52244. /**
  52245. * Parse properties from a JSON object
  52246. * @param serializationObject defines the JSON object
  52247. */
  52248. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52249. _super.prototype.parse.call(this, serializationObject);
  52250. this.direction1.copyFrom(serializationObject.direction1);
  52251. this.direction2.copyFrom(serializationObject.direction2);
  52252. };
  52253. return SphereDirectedParticleEmitter;
  52254. }(SphereParticleEmitter));
  52255. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52256. })(BABYLON || (BABYLON = {}));
  52257. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52258. var BABYLON;
  52259. (function (BABYLON) {
  52260. /**
  52261. * Represents one particle of a solid particle system.
  52262. * @see SolidParticleSystem
  52263. */
  52264. var SolidParticle = /** @class */ (function () {
  52265. /**
  52266. * Creates a Solid Particle object.
  52267. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52268. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52269. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52270. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52271. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52272. * @param shapeId (integer) is the model shape identifier in the SPS.
  52273. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52274. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52275. */
  52276. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52277. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52278. /**
  52279. * particle global index
  52280. */
  52281. this.idx = 0;
  52282. /**
  52283. * The color of the particle
  52284. */
  52285. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52286. /**
  52287. * The world space position of the particle.
  52288. */
  52289. this.position = BABYLON.Vector3.Zero();
  52290. /**
  52291. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52292. */
  52293. this.rotation = BABYLON.Vector3.Zero();
  52294. /**
  52295. * The scaling of the particle.
  52296. */
  52297. this.scaling = BABYLON.Vector3.One();
  52298. /**
  52299. * The uvs of the particle.
  52300. */
  52301. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52302. /**
  52303. * The current speed of the particle.
  52304. */
  52305. this.velocity = BABYLON.Vector3.Zero();
  52306. /**
  52307. * The pivot point in the particle local space.
  52308. */
  52309. this.pivot = BABYLON.Vector3.Zero();
  52310. /**
  52311. * Must the particle be translated from its pivot point in its local space ?
  52312. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52313. * Default : false
  52314. */
  52315. this.translateFromPivot = false;
  52316. /**
  52317. * Is the particle active or not ?
  52318. */
  52319. this.alive = true;
  52320. /**
  52321. * Is the particle visible or not ?
  52322. */
  52323. this.isVisible = true;
  52324. /**
  52325. * Index of this particle in the global "positions" array (Internal use)
  52326. */
  52327. this._pos = 0;
  52328. /**
  52329. * Index of this particle in the global "indices" array (Internal use)
  52330. */
  52331. this._ind = 0;
  52332. /**
  52333. * ModelShape id of this particle
  52334. */
  52335. this.shapeId = 0;
  52336. /**
  52337. * Index of the particle in its shape id (Internal use)
  52338. */
  52339. this.idxInShape = 0;
  52340. /**
  52341. * Still set as invisible in order to skip useless computations (Internal use)
  52342. */
  52343. this._stillInvisible = false;
  52344. /**
  52345. * Last computed particle rotation matrix
  52346. */
  52347. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52348. /**
  52349. * Parent particle Id, if any.
  52350. * Default null.
  52351. */
  52352. this.parentId = null;
  52353. /**
  52354. * Internal global position in the SPS.
  52355. */
  52356. this._globalPosition = BABYLON.Vector3.Zero();
  52357. this.idx = particleIndex;
  52358. this._pos = positionIndex;
  52359. this._ind = indiceIndex;
  52360. this._model = model;
  52361. this.shapeId = shapeId;
  52362. this.idxInShape = idxInShape;
  52363. this._sps = sps;
  52364. if (modelBoundingInfo) {
  52365. this._modelBoundingInfo = modelBoundingInfo;
  52366. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52367. }
  52368. }
  52369. Object.defineProperty(SolidParticle.prototype, "scale", {
  52370. /**
  52371. * Legacy support, changed scale to scaling
  52372. */
  52373. get: function () {
  52374. return this.scaling;
  52375. },
  52376. /**
  52377. * Legacy support, changed scale to scaling
  52378. */
  52379. set: function (scale) {
  52380. this.scaling = scale;
  52381. },
  52382. enumerable: true,
  52383. configurable: true
  52384. });
  52385. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52386. /**
  52387. * Legacy support, changed quaternion to rotationQuaternion
  52388. */
  52389. get: function () {
  52390. return this.rotationQuaternion;
  52391. },
  52392. /**
  52393. * Legacy support, changed quaternion to rotationQuaternion
  52394. */
  52395. set: function (q) {
  52396. this.rotationQuaternion = q;
  52397. },
  52398. enumerable: true,
  52399. configurable: true
  52400. });
  52401. /**
  52402. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52403. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52404. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52405. * @returns true if it intersects
  52406. */
  52407. SolidParticle.prototype.intersectsMesh = function (target) {
  52408. if (!this._boundingInfo || !target._boundingInfo) {
  52409. return false;
  52410. }
  52411. if (this._sps._bSphereOnly) {
  52412. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52413. }
  52414. return this._boundingInfo.intersects(target._boundingInfo, false);
  52415. };
  52416. return SolidParticle;
  52417. }());
  52418. BABYLON.SolidParticle = SolidParticle;
  52419. /**
  52420. * Represents the shape of the model used by one particle of a solid particle system.
  52421. * SPS internal tool, don't use it manually.
  52422. * @see SolidParticleSystem
  52423. */
  52424. var ModelShape = /** @class */ (function () {
  52425. /**
  52426. * 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.
  52427. * SPS internal tool, don't use it manually.
  52428. * @ignore
  52429. */
  52430. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52431. /**
  52432. * length of the shape in the model indices array (internal use)
  52433. */
  52434. this._indicesLength = 0;
  52435. this.shapeID = id;
  52436. this._shape = shape;
  52437. this._indicesLength = indicesLength;
  52438. this._shapeUV = shapeUV;
  52439. this._positionFunction = posFunction;
  52440. this._vertexFunction = vtxFunction;
  52441. }
  52442. return ModelShape;
  52443. }());
  52444. BABYLON.ModelShape = ModelShape;
  52445. /**
  52446. * Represents a Depth Sorted Particle in the solid particle system.
  52447. * @see SolidParticleSystem
  52448. */
  52449. var DepthSortedParticle = /** @class */ (function () {
  52450. function DepthSortedParticle() {
  52451. /**
  52452. * Index of the particle in the "indices" array
  52453. */
  52454. this.ind = 0;
  52455. /**
  52456. * Length of the particle shape in the "indices" array
  52457. */
  52458. this.indicesLength = 0;
  52459. /**
  52460. * Squared distance from the particle to the camera
  52461. */
  52462. this.sqDistance = 0.0;
  52463. }
  52464. return DepthSortedParticle;
  52465. }());
  52466. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52467. })(BABYLON || (BABYLON = {}));
  52468. //# sourceMappingURL=babylon.solidParticle.js.map
  52469. var BABYLON;
  52470. (function (BABYLON) {
  52471. /**
  52472. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52473. *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.
  52474. * The SPS is also a particle system. It provides some methods to manage the particles.
  52475. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52476. *
  52477. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52478. */
  52479. var SolidParticleSystem = /** @class */ (function () {
  52480. /**
  52481. * Creates a SPS (Solid Particle System) object.
  52482. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52483. * @param scene (Scene) is the scene in which the SPS is added.
  52484. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52485. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52486. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52487. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52488. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52489. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52490. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52491. */
  52492. function SolidParticleSystem(name, scene, options) {
  52493. /**
  52494. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52495. * Example : var p = SPS.particles[i];
  52496. */
  52497. this.particles = new Array();
  52498. /**
  52499. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52500. */
  52501. this.nbParticles = 0;
  52502. /**
  52503. * If the particles must ever face the camera (default false). Useful for planar particles.
  52504. */
  52505. this.billboard = false;
  52506. /**
  52507. * Recompute normals when adding a shape
  52508. */
  52509. this.recomputeNormals = true;
  52510. /**
  52511. * This a counter ofr your own usage. It's not set by any SPS functions.
  52512. */
  52513. this.counter = 0;
  52514. /**
  52515. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52516. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52517. */
  52518. this.vars = {};
  52519. /**
  52520. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52521. */
  52522. this._bSphereOnly = false;
  52523. /**
  52524. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52525. */
  52526. this._bSphereRadiusFactor = 1.0;
  52527. this._positions = new Array();
  52528. this._indices = new Array();
  52529. this._normals = new Array();
  52530. this._colors = new Array();
  52531. this._uvs = new Array();
  52532. this._index = 0; // indices index
  52533. this._updatable = true;
  52534. this._pickable = false;
  52535. this._isVisibilityBoxLocked = false;
  52536. this._alwaysVisible = false;
  52537. this._depthSort = false;
  52538. this._shapeCounter = 0;
  52539. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52540. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52541. this._computeParticleColor = true;
  52542. this._computeParticleTexture = true;
  52543. this._computeParticleRotation = true;
  52544. this._computeParticleVertex = false;
  52545. this._computeBoundingBox = false;
  52546. this._depthSortParticles = true;
  52547. this._cam_axisZ = BABYLON.Vector3.Zero();
  52548. this._cam_axisY = BABYLON.Vector3.Zero();
  52549. this._cam_axisX = BABYLON.Vector3.Zero();
  52550. this._axisZ = BABYLON.Axis.Z;
  52551. this._camDir = BABYLON.Vector3.Zero();
  52552. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52553. this._rotMatrix = new BABYLON.Matrix();
  52554. this._invertMatrix = new BABYLON.Matrix();
  52555. this._rotated = BABYLON.Vector3.Zero();
  52556. this._quaternion = new BABYLON.Quaternion();
  52557. this._vertex = BABYLON.Vector3.Zero();
  52558. this._normal = BABYLON.Vector3.Zero();
  52559. this._yaw = 0.0;
  52560. this._pitch = 0.0;
  52561. this._roll = 0.0;
  52562. this._halfroll = 0.0;
  52563. this._halfpitch = 0.0;
  52564. this._halfyaw = 0.0;
  52565. this._sinRoll = 0.0;
  52566. this._cosRoll = 0.0;
  52567. this._sinPitch = 0.0;
  52568. this._cosPitch = 0.0;
  52569. this._sinYaw = 0.0;
  52570. this._cosYaw = 0.0;
  52571. this._mustUnrotateFixedNormals = false;
  52572. this._minimum = BABYLON.Vector3.Zero();
  52573. this._maximum = BABYLON.Vector3.Zero();
  52574. this._minBbox = BABYLON.Vector3.Zero();
  52575. this._maxBbox = BABYLON.Vector3.Zero();
  52576. this._particlesIntersect = false;
  52577. this._depthSortFunction = function (p1, p2) {
  52578. return (p2.sqDistance - p1.sqDistance);
  52579. };
  52580. this._needs32Bits = false;
  52581. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52582. this._scaledPivot = BABYLON.Vector3.Zero();
  52583. this._particleHasParent = false;
  52584. this.name = name;
  52585. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52586. this._camera = scene.activeCamera;
  52587. this._pickable = options ? options.isPickable : false;
  52588. this._depthSort = options ? options.enableDepthSort : false;
  52589. this._particlesIntersect = options ? options.particleIntersection : false;
  52590. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52591. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52592. if (options && options.updatable) {
  52593. this._updatable = options.updatable;
  52594. }
  52595. else {
  52596. this._updatable = true;
  52597. }
  52598. if (this._pickable) {
  52599. this.pickedParticles = [];
  52600. }
  52601. if (this._depthSort) {
  52602. this.depthSortedParticles = [];
  52603. }
  52604. }
  52605. /**
  52606. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52607. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52608. * @returns the created mesh
  52609. */
  52610. SolidParticleSystem.prototype.buildMesh = function () {
  52611. if (this.nbParticles === 0) {
  52612. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52613. this.addShape(triangle, 1);
  52614. triangle.dispose();
  52615. }
  52616. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52617. this._positions32 = new Float32Array(this._positions);
  52618. this._uvs32 = new Float32Array(this._uvs);
  52619. this._colors32 = new Float32Array(this._colors);
  52620. if (this.recomputeNormals) {
  52621. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52622. }
  52623. this._normals32 = new Float32Array(this._normals);
  52624. this._fixedNormal32 = new Float32Array(this._normals);
  52625. if (this._mustUnrotateFixedNormals) {
  52626. this._unrotateFixedNormals();
  52627. }
  52628. var vertexData = new BABYLON.VertexData();
  52629. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52630. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52631. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52632. if (this._uvs32) {
  52633. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52634. ;
  52635. }
  52636. if (this._colors32) {
  52637. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52638. }
  52639. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52640. vertexData.applyToMesh(mesh, this._updatable);
  52641. this.mesh = mesh;
  52642. this.mesh.isPickable = this._pickable;
  52643. // free memory
  52644. if (!this._depthSort) {
  52645. this._indices = null;
  52646. }
  52647. this._positions = null;
  52648. this._normals = null;
  52649. this._uvs = null;
  52650. this._colors = null;
  52651. if (!this._updatable) {
  52652. this.particles.length = 0;
  52653. }
  52654. return mesh;
  52655. };
  52656. /**
  52657. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52658. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52659. * Thus the particles generated from `digest()` have their property `position` set yet.
  52660. * @param mesh ( Mesh ) is the mesh to be digested
  52661. * @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
  52662. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52663. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52664. * @returns the current SPS
  52665. */
  52666. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52667. var size = (options && options.facetNb) || 1;
  52668. var number = (options && options.number) || 0;
  52669. var delta = (options && options.delta) || 0;
  52670. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52671. var meshInd = mesh.getIndices();
  52672. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52673. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52674. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52675. var f = 0; // facet counter
  52676. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52677. // compute size from number
  52678. if (number) {
  52679. number = (number > totalFacets) ? totalFacets : number;
  52680. size = Math.round(totalFacets / number);
  52681. delta = 0;
  52682. }
  52683. else {
  52684. size = (size > totalFacets) ? totalFacets : size;
  52685. }
  52686. var facetPos = []; // submesh positions
  52687. var facetInd = []; // submesh indices
  52688. var facetUV = []; // submesh UV
  52689. var facetCol = []; // submesh colors
  52690. var barycenter = BABYLON.Vector3.Zero();
  52691. var sizeO = size;
  52692. while (f < totalFacets) {
  52693. size = sizeO + Math.floor((1 + delta) * Math.random());
  52694. if (f > totalFacets - size) {
  52695. size = totalFacets - f;
  52696. }
  52697. // reset temp arrays
  52698. facetPos.length = 0;
  52699. facetInd.length = 0;
  52700. facetUV.length = 0;
  52701. facetCol.length = 0;
  52702. // iterate over "size" facets
  52703. var fi = 0;
  52704. for (var j = f * 3; j < (f + size) * 3; j++) {
  52705. facetInd.push(fi);
  52706. var i = meshInd[j];
  52707. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52708. if (meshUV) {
  52709. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52710. }
  52711. if (meshCol) {
  52712. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52713. }
  52714. fi++;
  52715. }
  52716. // create a model shape for each single particle
  52717. var idx = this.nbParticles;
  52718. var shape = this._posToShape(facetPos);
  52719. var shapeUV = this._uvsToShapeUV(facetUV);
  52720. // compute the barycenter of the shape
  52721. var v;
  52722. for (v = 0; v < shape.length; v++) {
  52723. barycenter.addInPlace(shape[v]);
  52724. }
  52725. barycenter.scaleInPlace(1 / shape.length);
  52726. // shift the shape from its barycenter to the origin
  52727. for (v = 0; v < shape.length; v++) {
  52728. shape[v].subtractInPlace(barycenter);
  52729. }
  52730. var bInfo;
  52731. if (this._particlesIntersect) {
  52732. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52733. }
  52734. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52735. // add the particle in the SPS
  52736. var currentPos = this._positions.length;
  52737. var currentInd = this._indices.length;
  52738. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52739. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52740. // initialize the particle position
  52741. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52742. this._index += shape.length;
  52743. idx++;
  52744. this.nbParticles++;
  52745. this._shapeCounter++;
  52746. f += size;
  52747. }
  52748. return this;
  52749. };
  52750. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52751. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52752. var index = 0;
  52753. var idx = 0;
  52754. for (var p = 0; p < this.particles.length; p++) {
  52755. this._particle = this.particles[p];
  52756. this._shape = this._particle._model._shape;
  52757. if (this._particle.rotationQuaternion) {
  52758. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52759. }
  52760. else {
  52761. this._yaw = this._particle.rotation.y;
  52762. this._pitch = this._particle.rotation.x;
  52763. this._roll = this._particle.rotation.z;
  52764. this._quaternionRotationYPR();
  52765. }
  52766. this._quaternionToRotationMatrix();
  52767. this._rotMatrix.invertToRef(this._invertMatrix);
  52768. for (var pt = 0; pt < this._shape.length; pt++) {
  52769. idx = index + pt * 3;
  52770. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52771. this._fixedNormal32[idx] = this._normal.x;
  52772. this._fixedNormal32[idx + 1] = this._normal.y;
  52773. this._fixedNormal32[idx + 2] = this._normal.z;
  52774. }
  52775. index = idx + 3;
  52776. }
  52777. };
  52778. //reset copy
  52779. SolidParticleSystem.prototype._resetCopy = function () {
  52780. this._copy.position.x = 0;
  52781. this._copy.position.y = 0;
  52782. this._copy.position.z = 0;
  52783. this._copy.rotation.x = 0;
  52784. this._copy.rotation.y = 0;
  52785. this._copy.rotation.z = 0;
  52786. this._copy.rotationQuaternion = null;
  52787. this._copy.scaling.x = 1.0;
  52788. this._copy.scaling.y = 1.0;
  52789. this._copy.scaling.z = 1.0;
  52790. this._copy.uvs.x = 0;
  52791. this._copy.uvs.y = 0;
  52792. this._copy.uvs.z = 1.0;
  52793. this._copy.uvs.w = 1.0;
  52794. this._copy.color = null;
  52795. this._copy.translateFromPivot = false;
  52796. };
  52797. // _meshBuilder : inserts the shape model in the global SPS mesh
  52798. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52799. var i;
  52800. var u = 0;
  52801. var c = 0;
  52802. var n = 0;
  52803. this._resetCopy();
  52804. if (options && options.positionFunction) {
  52805. options.positionFunction(this._copy, idx, idxInShape);
  52806. this._mustUnrotateFixedNormals = true;
  52807. }
  52808. if (this._copy.rotationQuaternion) {
  52809. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52810. }
  52811. else {
  52812. this._yaw = this._copy.rotation.y;
  52813. this._pitch = this._copy.rotation.x;
  52814. this._roll = this._copy.rotation.z;
  52815. this._quaternionRotationYPR();
  52816. }
  52817. this._quaternionToRotationMatrix();
  52818. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52819. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52820. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52821. if (this._copy.translateFromPivot) {
  52822. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52823. }
  52824. else {
  52825. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52826. }
  52827. for (i = 0; i < shape.length; i++) {
  52828. this._vertex.x = shape[i].x;
  52829. this._vertex.y = shape[i].y;
  52830. this._vertex.z = shape[i].z;
  52831. if (options && options.vertexFunction) {
  52832. options.vertexFunction(this._copy, this._vertex, i);
  52833. }
  52834. this._vertex.x *= this._copy.scaling.x;
  52835. this._vertex.y *= this._copy.scaling.y;
  52836. this._vertex.z *= this._copy.scaling.z;
  52837. this._vertex.x -= this._scaledPivot.x;
  52838. this._vertex.y -= this._scaledPivot.y;
  52839. this._vertex.z -= this._scaledPivot.z;
  52840. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52841. this._rotated.addInPlace(this._pivotBackTranslation);
  52842. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52843. if (meshUV) {
  52844. 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);
  52845. u += 2;
  52846. }
  52847. if (this._copy.color) {
  52848. this._color = this._copy.color;
  52849. }
  52850. else if (meshCol && meshCol[c] !== undefined) {
  52851. this._color.r = meshCol[c];
  52852. this._color.g = meshCol[c + 1];
  52853. this._color.b = meshCol[c + 2];
  52854. this._color.a = meshCol[c + 3];
  52855. }
  52856. else {
  52857. this._color.r = 1.0;
  52858. this._color.g = 1.0;
  52859. this._color.b = 1.0;
  52860. this._color.a = 1.0;
  52861. }
  52862. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52863. c += 4;
  52864. if (!this.recomputeNormals && meshNor) {
  52865. this._normal.x = meshNor[n];
  52866. this._normal.y = meshNor[n + 1];
  52867. this._normal.z = meshNor[n + 2];
  52868. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52869. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52870. n += 3;
  52871. }
  52872. }
  52873. for (i = 0; i < meshInd.length; i++) {
  52874. var current_ind = p + meshInd[i];
  52875. indices.push(current_ind);
  52876. if (current_ind > 65535) {
  52877. this._needs32Bits = true;
  52878. }
  52879. }
  52880. if (this._pickable) {
  52881. var nbfaces = meshInd.length / 3;
  52882. for (i = 0; i < nbfaces; i++) {
  52883. this.pickedParticles.push({ idx: idx, faceId: i });
  52884. }
  52885. }
  52886. if (this._depthSort) {
  52887. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52888. }
  52889. return this._copy;
  52890. };
  52891. // returns a shape array from positions array
  52892. SolidParticleSystem.prototype._posToShape = function (positions) {
  52893. var shape = [];
  52894. for (var i = 0; i < positions.length; i += 3) {
  52895. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52896. }
  52897. return shape;
  52898. };
  52899. // returns a shapeUV array from a Vector4 uvs
  52900. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52901. var shapeUV = [];
  52902. if (uvs) {
  52903. for (var i = 0; i < uvs.length; i++)
  52904. shapeUV.push(uvs[i]);
  52905. }
  52906. return shapeUV;
  52907. };
  52908. // adds a new particle object in the particles array
  52909. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52910. if (bInfo === void 0) { bInfo = null; }
  52911. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52912. this.particles.push(sp);
  52913. return sp;
  52914. };
  52915. /**
  52916. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52917. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52918. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52919. * @param nb (positive integer) the number of particles to be created from this model
  52920. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52921. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52922. * @returns the number of shapes in the system
  52923. */
  52924. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52925. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52926. var meshInd = mesh.getIndices();
  52927. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52928. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52929. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52930. var bbInfo;
  52931. if (this._particlesIntersect) {
  52932. bbInfo = mesh.getBoundingInfo();
  52933. }
  52934. var shape = this._posToShape(meshPos);
  52935. var shapeUV = this._uvsToShapeUV(meshUV);
  52936. var posfunc = options ? options.positionFunction : null;
  52937. var vtxfunc = options ? options.vertexFunction : null;
  52938. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52939. // particles
  52940. var sp;
  52941. var currentCopy;
  52942. var idx = this.nbParticles;
  52943. for (var i = 0; i < nb; i++) {
  52944. var currentPos = this._positions.length;
  52945. var currentInd = this._indices.length;
  52946. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52947. if (this._updatable) {
  52948. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52949. sp.position.copyFrom(currentCopy.position);
  52950. sp.rotation.copyFrom(currentCopy.rotation);
  52951. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52952. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52953. }
  52954. if (currentCopy.color && sp.color) {
  52955. sp.color.copyFrom(currentCopy.color);
  52956. }
  52957. sp.scaling.copyFrom(currentCopy.scaling);
  52958. sp.uvs.copyFrom(currentCopy.uvs);
  52959. }
  52960. this._index += shape.length;
  52961. idx++;
  52962. }
  52963. this.nbParticles += nb;
  52964. this._shapeCounter++;
  52965. return this._shapeCounter - 1;
  52966. };
  52967. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52968. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52969. this._resetCopy();
  52970. if (particle._model._positionFunction) {
  52971. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52972. }
  52973. if (this._copy.rotationQuaternion) {
  52974. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52975. }
  52976. else {
  52977. this._yaw = this._copy.rotation.y;
  52978. this._pitch = this._copy.rotation.x;
  52979. this._roll = this._copy.rotation.z;
  52980. this._quaternionRotationYPR();
  52981. }
  52982. this._quaternionToRotationMatrix();
  52983. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52984. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52985. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52986. if (this._copy.translateFromPivot) {
  52987. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52988. }
  52989. else {
  52990. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52991. }
  52992. this._shape = particle._model._shape;
  52993. for (var pt = 0; pt < this._shape.length; pt++) {
  52994. this._vertex.x = this._shape[pt].x;
  52995. this._vertex.y = this._shape[pt].y;
  52996. this._vertex.z = this._shape[pt].z;
  52997. if (particle._model._vertexFunction) {
  52998. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52999. }
  53000. this._vertex.x *= this._copy.scaling.x;
  53001. this._vertex.y *= this._copy.scaling.y;
  53002. this._vertex.z *= this._copy.scaling.z;
  53003. this._vertex.x -= this._scaledPivot.x;
  53004. this._vertex.y -= this._scaledPivot.y;
  53005. this._vertex.z -= this._scaledPivot.z;
  53006. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53007. this._rotated.addInPlace(this._pivotBackTranslation);
  53008. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53009. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53010. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53011. }
  53012. particle.position.x = 0.0;
  53013. particle.position.y = 0.0;
  53014. particle.position.z = 0.0;
  53015. particle.rotation.x = 0.0;
  53016. particle.rotation.y = 0.0;
  53017. particle.rotation.z = 0.0;
  53018. particle.rotationQuaternion = null;
  53019. particle.scaling.x = 1.0;
  53020. particle.scaling.y = 1.0;
  53021. particle.scaling.z = 1.0;
  53022. particle.uvs.x = 0.0;
  53023. particle.uvs.y = 0.0;
  53024. particle.uvs.z = 1.0;
  53025. particle.uvs.w = 1.0;
  53026. particle.pivot.x = 0.0;
  53027. particle.pivot.y = 0.0;
  53028. particle.pivot.z = 0.0;
  53029. particle.translateFromPivot = false;
  53030. particle.parentId = null;
  53031. };
  53032. /**
  53033. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53034. * @returns the SPS.
  53035. */
  53036. SolidParticleSystem.prototype.rebuildMesh = function () {
  53037. for (var p = 0; p < this.particles.length; p++) {
  53038. this._rebuildParticle(this.particles[p]);
  53039. }
  53040. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53041. return this;
  53042. };
  53043. /**
  53044. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53045. * This method calls `updateParticle()` for each particle of the SPS.
  53046. * For an animated SPS, it is usually called within the render loop.
  53047. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53048. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53049. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53050. * @returns the SPS.
  53051. */
  53052. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53053. if (start === void 0) { start = 0; }
  53054. if (end === void 0) { end = this.nbParticles - 1; }
  53055. if (update === void 0) { update = true; }
  53056. if (!this._updatable) {
  53057. return this;
  53058. }
  53059. // custom beforeUpdate
  53060. this.beforeUpdateParticles(start, end, update);
  53061. this._cam_axisX.x = 1.0;
  53062. this._cam_axisX.y = 0.0;
  53063. this._cam_axisX.z = 0.0;
  53064. this._cam_axisY.x = 0.0;
  53065. this._cam_axisY.y = 1.0;
  53066. this._cam_axisY.z = 0.0;
  53067. this._cam_axisZ.x = 0.0;
  53068. this._cam_axisZ.y = 0.0;
  53069. this._cam_axisZ.z = 1.0;
  53070. // cases when the World Matrix is to be computed first
  53071. if (this.billboard || this._depthSort) {
  53072. this.mesh.computeWorldMatrix(true);
  53073. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53074. }
  53075. // if the particles will always face the camera
  53076. if (this.billboard) {
  53077. // compute the camera position and un-rotate it by the current mesh rotation
  53078. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53079. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53080. this._cam_axisZ.normalize();
  53081. // same for camera up vector extracted from the cam view matrix
  53082. var view = this._camera.getViewMatrix(true);
  53083. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53084. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53085. this._cam_axisY.normalize();
  53086. this._cam_axisX.normalize();
  53087. }
  53088. // if depthSort, compute the camera global position in the mesh local system
  53089. if (this._depthSort) {
  53090. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53091. }
  53092. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53093. var idx = 0; // current position index in the global array positions32
  53094. var index = 0; // position start index in the global array positions32 of the current particle
  53095. var colidx = 0; // current color index in the global array colors32
  53096. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53097. var uvidx = 0; // current uv index in the global array uvs32
  53098. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53099. var pt = 0; // current index in the particle model shape
  53100. if (this.mesh.isFacetDataEnabled) {
  53101. this._computeBoundingBox = true;
  53102. }
  53103. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53104. if (this._computeBoundingBox) {
  53105. if (start == 0 && end == this.nbParticles - 1) {
  53106. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53107. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53108. }
  53109. else {
  53110. if (this.mesh._boundingInfo) {
  53111. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53112. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53113. }
  53114. }
  53115. }
  53116. // particle loop
  53117. index = this.particles[start]._pos;
  53118. var vpos = (index / 3) | 0;
  53119. colorIndex = vpos * 4;
  53120. uvIndex = vpos * 2;
  53121. for (var p = start; p <= end; p++) {
  53122. this._particle = this.particles[p];
  53123. this._shape = this._particle._model._shape;
  53124. this._shapeUV = this._particle._model._shapeUV;
  53125. // call to custom user function to update the particle properties
  53126. this.updateParticle(this._particle);
  53127. // camera-particle distance for depth sorting
  53128. if (this._depthSort && this._depthSortParticles) {
  53129. var dsp = this.depthSortedParticles[p];
  53130. dsp.ind = this._particle._ind;
  53131. dsp.indicesLength = this._particle._model._indicesLength;
  53132. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53133. }
  53134. // skip the computations for inactive or already invisible particles
  53135. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53136. // increment indexes for the next particle
  53137. pt = this._shape.length;
  53138. index += pt * 3;
  53139. colorIndex += pt * 4;
  53140. uvIndex += pt * 2;
  53141. continue;
  53142. }
  53143. if (this._particle.isVisible) {
  53144. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53145. this._particleHasParent = (this._particle.parentId !== null);
  53146. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53147. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53148. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53149. // particle rotation matrix
  53150. if (this.billboard) {
  53151. this._particle.rotation.x = 0.0;
  53152. this._particle.rotation.y = 0.0;
  53153. }
  53154. if (this._computeParticleRotation || this.billboard) {
  53155. if (this._particle.rotationQuaternion) {
  53156. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53157. }
  53158. else {
  53159. this._yaw = this._particle.rotation.y;
  53160. this._pitch = this._particle.rotation.x;
  53161. this._roll = this._particle.rotation.z;
  53162. this._quaternionRotationYPR();
  53163. }
  53164. this._quaternionToRotationMatrix();
  53165. }
  53166. if (this._particleHasParent) {
  53167. this._parent = this.particles[this._particle.parentId];
  53168. 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];
  53169. 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];
  53170. 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];
  53171. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53172. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53173. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53174. if (this._computeParticleRotation || this.billboard) {
  53175. 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];
  53176. 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];
  53177. 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];
  53178. 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];
  53179. 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];
  53180. 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];
  53181. 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];
  53182. 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];
  53183. 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];
  53184. }
  53185. }
  53186. else {
  53187. this._particle._globalPosition.x = this._particle.position.x;
  53188. this._particle._globalPosition.y = this._particle.position.y;
  53189. this._particle._globalPosition.z = this._particle.position.z;
  53190. if (this._computeParticleRotation || this.billboard) {
  53191. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53192. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53193. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53194. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53195. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53196. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53197. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53198. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53199. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53200. }
  53201. }
  53202. if (this._particle.translateFromPivot) {
  53203. this._pivotBackTranslation.x = 0.0;
  53204. this._pivotBackTranslation.y = 0.0;
  53205. this._pivotBackTranslation.z = 0.0;
  53206. }
  53207. else {
  53208. this._pivotBackTranslation.x = this._scaledPivot.x;
  53209. this._pivotBackTranslation.y = this._scaledPivot.y;
  53210. this._pivotBackTranslation.z = this._scaledPivot.z;
  53211. }
  53212. // particle vertex loop
  53213. for (pt = 0; pt < this._shape.length; pt++) {
  53214. idx = index + pt * 3;
  53215. colidx = colorIndex + pt * 4;
  53216. uvidx = uvIndex + pt * 2;
  53217. this._vertex.x = this._shape[pt].x;
  53218. this._vertex.y = this._shape[pt].y;
  53219. this._vertex.z = this._shape[pt].z;
  53220. if (this._computeParticleVertex) {
  53221. this.updateParticleVertex(this._particle, this._vertex, pt);
  53222. }
  53223. // positions
  53224. this._vertex.x *= this._particle.scaling.x;
  53225. this._vertex.y *= this._particle.scaling.y;
  53226. this._vertex.z *= this._particle.scaling.z;
  53227. this._vertex.x -= this._scaledPivot.x;
  53228. this._vertex.y -= this._scaledPivot.y;
  53229. this._vertex.z -= this._scaledPivot.z;
  53230. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53231. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53232. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53233. this._rotated.x += this._pivotBackTranslation.x;
  53234. this._rotated.y += this._pivotBackTranslation.y;
  53235. this._rotated.z += this._pivotBackTranslation.z;
  53236. 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;
  53237. 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;
  53238. 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;
  53239. if (this._computeBoundingBox) {
  53240. if (this._positions32[idx] < this._minimum.x) {
  53241. this._minimum.x = this._positions32[idx];
  53242. }
  53243. if (this._positions32[idx] > this._maximum.x) {
  53244. this._maximum.x = this._positions32[idx];
  53245. }
  53246. if (this._positions32[idx + 1] < this._minimum.y) {
  53247. this._minimum.y = this._positions32[idx + 1];
  53248. }
  53249. if (this._positions32[idx + 1] > this._maximum.y) {
  53250. this._maximum.y = this._positions32[idx + 1];
  53251. }
  53252. if (this._positions32[idx + 2] < this._minimum.z) {
  53253. this._minimum.z = this._positions32[idx + 2];
  53254. }
  53255. if (this._positions32[idx + 2] > this._maximum.z) {
  53256. this._maximum.z = this._positions32[idx + 2];
  53257. }
  53258. }
  53259. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53260. if (!this._computeParticleVertex) {
  53261. this._normal.x = this._fixedNormal32[idx];
  53262. this._normal.y = this._fixedNormal32[idx + 1];
  53263. this._normal.z = this._fixedNormal32[idx + 2];
  53264. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53265. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53266. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53267. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53268. 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;
  53269. 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;
  53270. }
  53271. if (this._computeParticleColor && this._particle.color) {
  53272. this._colors32[colidx] = this._particle.color.r;
  53273. this._colors32[colidx + 1] = this._particle.color.g;
  53274. this._colors32[colidx + 2] = this._particle.color.b;
  53275. this._colors32[colidx + 3] = this._particle.color.a;
  53276. }
  53277. if (this._computeParticleTexture) {
  53278. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53279. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53280. }
  53281. }
  53282. }
  53283. else {
  53284. this._particle._stillInvisible = true; // mark the particle as invisible
  53285. for (pt = 0; pt < this._shape.length; pt++) {
  53286. idx = index + pt * 3;
  53287. colidx = colorIndex + pt * 4;
  53288. uvidx = uvIndex + pt * 2;
  53289. this._positions32[idx] = 0.0;
  53290. this._positions32[idx + 1] = 0.0;
  53291. this._positions32[idx + 2] = 0.0;
  53292. this._normals32[idx] = 0.0;
  53293. this._normals32[idx + 1] = 0.0;
  53294. this._normals32[idx + 2] = 0.0;
  53295. if (this._computeParticleColor && this._particle.color) {
  53296. this._colors32[colidx] = this._particle.color.r;
  53297. this._colors32[colidx + 1] = this._particle.color.g;
  53298. this._colors32[colidx + 2] = this._particle.color.b;
  53299. this._colors32[colidx + 3] = this._particle.color.a;
  53300. }
  53301. if (this._computeParticleTexture) {
  53302. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53303. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53304. }
  53305. }
  53306. }
  53307. // if the particle intersections must be computed : update the bbInfo
  53308. if (this._particlesIntersect) {
  53309. var bInfo = this._particle._boundingInfo;
  53310. var bBox = bInfo.boundingBox;
  53311. var bSphere = bInfo.boundingSphere;
  53312. if (!this._bSphereOnly) {
  53313. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53314. for (var b = 0; b < bBox.vectors.length; b++) {
  53315. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53316. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53317. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53318. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53319. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53320. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53321. 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;
  53322. 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;
  53323. 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;
  53324. }
  53325. bBox._update(this.mesh._worldMatrix);
  53326. }
  53327. // place and scale the particle bouding sphere in the SPS local system, then update it
  53328. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53329. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53330. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53331. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53332. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53333. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53334. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53335. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53336. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53337. 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));
  53338. bSphere._update(this.mesh._worldMatrix);
  53339. }
  53340. // increment indexes for the next particle
  53341. index = idx + 3;
  53342. colorIndex = colidx + 4;
  53343. uvIndex = uvidx + 2;
  53344. }
  53345. // if the VBO must be updated
  53346. if (update) {
  53347. if (this._computeParticleColor) {
  53348. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53349. }
  53350. if (this._computeParticleTexture) {
  53351. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53352. }
  53353. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53354. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53355. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53356. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53357. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53358. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53359. for (var i = 0; i < this._normals32.length; i++) {
  53360. this._fixedNormal32[i] = this._normals32[i];
  53361. }
  53362. }
  53363. if (!this.mesh.areNormalsFrozen) {
  53364. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53365. }
  53366. }
  53367. if (this._depthSort && this._depthSortParticles) {
  53368. this.depthSortedParticles.sort(this._depthSortFunction);
  53369. var dspl = this.depthSortedParticles.length;
  53370. var sorted = 0;
  53371. var lind = 0;
  53372. var sind = 0;
  53373. var sid = 0;
  53374. for (sorted = 0; sorted < dspl; sorted++) {
  53375. lind = this.depthSortedParticles[sorted].indicesLength;
  53376. sind = this.depthSortedParticles[sorted].ind;
  53377. for (var i = 0; i < lind; i++) {
  53378. this._indices32[sid] = this._indices[sind + i];
  53379. sid++;
  53380. }
  53381. }
  53382. this.mesh.updateIndices(this._indices32);
  53383. }
  53384. }
  53385. if (this._computeBoundingBox) {
  53386. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53387. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53388. }
  53389. this.afterUpdateParticles(start, end, update);
  53390. return this;
  53391. };
  53392. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53393. this._halfroll = this._roll * 0.5;
  53394. this._halfpitch = this._pitch * 0.5;
  53395. this._halfyaw = this._yaw * 0.5;
  53396. this._sinRoll = Math.sin(this._halfroll);
  53397. this._cosRoll = Math.cos(this._halfroll);
  53398. this._sinPitch = Math.sin(this._halfpitch);
  53399. this._cosPitch = Math.cos(this._halfpitch);
  53400. this._sinYaw = Math.sin(this._halfyaw);
  53401. this._cosYaw = Math.cos(this._halfyaw);
  53402. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53403. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53404. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53405. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53406. };
  53407. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53408. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53409. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53410. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53411. this._rotMatrix.m[3] = 0;
  53412. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53413. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53414. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53415. this._rotMatrix.m[7] = 0;
  53416. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53417. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53418. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53419. this._rotMatrix.m[11] = 0;
  53420. this._rotMatrix.m[12] = 0;
  53421. this._rotMatrix.m[13] = 0;
  53422. this._rotMatrix.m[14] = 0;
  53423. this._rotMatrix.m[15] = 1.0;
  53424. };
  53425. /**
  53426. * Disposes the SPS.
  53427. */
  53428. SolidParticleSystem.prototype.dispose = function () {
  53429. this.mesh.dispose();
  53430. this.vars = null;
  53431. // drop references to internal big arrays for the GC
  53432. this._positions = null;
  53433. this._indices = null;
  53434. this._normals = null;
  53435. this._uvs = null;
  53436. this._colors = null;
  53437. this._indices32 = null;
  53438. this._positions32 = null;
  53439. this._normals32 = null;
  53440. this._fixedNormal32 = null;
  53441. this._uvs32 = null;
  53442. this._colors32 = null;
  53443. this.pickedParticles = null;
  53444. };
  53445. /**
  53446. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53447. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53448. * @returns the SPS.
  53449. */
  53450. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53451. if (!this._isVisibilityBoxLocked) {
  53452. this.mesh.refreshBoundingInfo();
  53453. }
  53454. return this;
  53455. };
  53456. /**
  53457. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53458. * @param size the size (float) of the visibility box
  53459. * note : this doesn't lock the SPS mesh bounding box.
  53460. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53461. */
  53462. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53463. var vis = size / 2;
  53464. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53465. };
  53466. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53467. /**
  53468. * Gets whether the SPS as always visible or not
  53469. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53470. */
  53471. get: function () {
  53472. return this._alwaysVisible;
  53473. },
  53474. /**
  53475. * Sets the SPS as always visible or not
  53476. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53477. */
  53478. set: function (val) {
  53479. this._alwaysVisible = val;
  53480. this.mesh.alwaysSelectAsActiveMesh = val;
  53481. },
  53482. enumerable: true,
  53483. configurable: true
  53484. });
  53485. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53486. /**
  53487. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53488. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53489. */
  53490. get: function () {
  53491. return this._isVisibilityBoxLocked;
  53492. },
  53493. /**
  53494. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53495. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53496. */
  53497. set: function (val) {
  53498. this._isVisibilityBoxLocked = val;
  53499. var boundingInfo = this.mesh.getBoundingInfo();
  53500. boundingInfo.isLocked = val;
  53501. },
  53502. enumerable: true,
  53503. configurable: true
  53504. });
  53505. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53506. /**
  53507. * Gets if `setParticles()` computes the particle rotations or not.
  53508. * Default value : true. The SPS is faster when it's set to false.
  53509. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53510. */
  53511. get: function () {
  53512. return this._computeParticleRotation;
  53513. },
  53514. /**
  53515. * Tells to `setParticles()` to compute the particle rotations or not.
  53516. * Default value : true. The SPS is faster when it's set to false.
  53517. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53518. */
  53519. set: function (val) {
  53520. this._computeParticleRotation = val;
  53521. },
  53522. enumerable: true,
  53523. configurable: true
  53524. });
  53525. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53526. /**
  53527. * Gets if `setParticles()` computes the particle colors or not.
  53528. * Default value : true. The SPS is faster when it's set to false.
  53529. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53530. */
  53531. get: function () {
  53532. return this._computeParticleColor;
  53533. },
  53534. /**
  53535. * Tells to `setParticles()` to compute the particle colors or not.
  53536. * Default value : true. The SPS is faster when it's set to false.
  53537. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53538. */
  53539. set: function (val) {
  53540. this._computeParticleColor = val;
  53541. },
  53542. enumerable: true,
  53543. configurable: true
  53544. });
  53545. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53546. /**
  53547. * Gets if `setParticles()` computes the particle textures or not.
  53548. * Default value : true. The SPS is faster when it's set to false.
  53549. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53550. */
  53551. get: function () {
  53552. return this._computeParticleTexture;
  53553. },
  53554. set: function (val) {
  53555. this._computeParticleTexture = val;
  53556. },
  53557. enumerable: true,
  53558. configurable: true
  53559. });
  53560. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53561. /**
  53562. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53563. * Default value : false. The SPS is faster when it's set to false.
  53564. * Note : the particle custom vertex positions aren't stored values.
  53565. */
  53566. get: function () {
  53567. return this._computeParticleVertex;
  53568. },
  53569. /**
  53570. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53571. * Default value : false. The SPS is faster when it's set to false.
  53572. * Note : the particle custom vertex positions aren't stored values.
  53573. */
  53574. set: function (val) {
  53575. this._computeParticleVertex = val;
  53576. },
  53577. enumerable: true,
  53578. configurable: true
  53579. });
  53580. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53581. /**
  53582. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53583. */
  53584. get: function () {
  53585. return this._computeBoundingBox;
  53586. },
  53587. /**
  53588. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53589. */
  53590. set: function (val) {
  53591. this._computeBoundingBox = val;
  53592. },
  53593. enumerable: true,
  53594. configurable: true
  53595. });
  53596. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53597. /**
  53598. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53599. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53600. * Default : `true`
  53601. */
  53602. get: function () {
  53603. return this._depthSortParticles;
  53604. },
  53605. /**
  53606. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53607. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53608. * Default : `true`
  53609. */
  53610. set: function (val) {
  53611. this._depthSortParticles = val;
  53612. },
  53613. enumerable: true,
  53614. configurable: true
  53615. });
  53616. // =======================================================================
  53617. // Particle behavior logic
  53618. // these following methods may be overwritten by the user to fit his needs
  53619. /**
  53620. * This function does nothing. It may be overwritten to set all the particle first values.
  53621. * The SPS doesn't call this function, you may have to call it by your own.
  53622. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53623. */
  53624. SolidParticleSystem.prototype.initParticles = function () {
  53625. };
  53626. /**
  53627. * This function does nothing. It may be overwritten to recycle a particle.
  53628. * The SPS doesn't call this function, you may have to call it by your own.
  53629. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53630. * @param particle The particle to recycle
  53631. * @returns the recycled particle
  53632. */
  53633. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53634. return particle;
  53635. };
  53636. /**
  53637. * Updates a particle : this function should be overwritten by the user.
  53638. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53639. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53640. * @example : just set a particle position or velocity and recycle conditions
  53641. * @param particle The particle to update
  53642. * @returns the updated particle
  53643. */
  53644. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53645. return particle;
  53646. };
  53647. /**
  53648. * Updates a vertex of a particle : it can be overwritten by the user.
  53649. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53650. * @param particle the current particle
  53651. * @param vertex the current index of the current particle
  53652. * @param pt the index of the current vertex in the particle shape
  53653. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53654. * @example : just set a vertex particle position
  53655. * @returns the updated vertex
  53656. */
  53657. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53658. return vertex;
  53659. };
  53660. /**
  53661. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53662. * This does nothing and may be overwritten by the user.
  53663. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53664. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53665. * @param update the boolean update value actually passed to setParticles()
  53666. */
  53667. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53668. };
  53669. /**
  53670. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53671. * This will be passed three parameters.
  53672. * This does nothing and may be overwritten by the user.
  53673. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53674. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53675. * @param update the boolean update value actually passed to setParticles()
  53676. */
  53677. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53678. };
  53679. return SolidParticleSystem;
  53680. }());
  53681. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53682. })(BABYLON || (BABYLON = {}));
  53683. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53684. var BABYLON;
  53685. (function (BABYLON) {
  53686. var ShaderMaterial = /** @class */ (function (_super) {
  53687. __extends(ShaderMaterial, _super);
  53688. function ShaderMaterial(name, scene, shaderPath, options) {
  53689. var _this = _super.call(this, name, scene) || this;
  53690. _this._textures = {};
  53691. _this._textureArrays = {};
  53692. _this._floats = {};
  53693. _this._ints = {};
  53694. _this._floatsArrays = {};
  53695. _this._colors3 = {};
  53696. _this._colors3Arrays = {};
  53697. _this._colors4 = {};
  53698. _this._vectors2 = {};
  53699. _this._vectors3 = {};
  53700. _this._vectors4 = {};
  53701. _this._matrices = {};
  53702. _this._matrices3x3 = {};
  53703. _this._matrices2x2 = {};
  53704. _this._vectors2Arrays = {};
  53705. _this._vectors3Arrays = {};
  53706. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53707. _this._shaderPath = shaderPath;
  53708. options.needAlphaBlending = options.needAlphaBlending || false;
  53709. options.needAlphaTesting = options.needAlphaTesting || false;
  53710. options.attributes = options.attributes || ["position", "normal", "uv"];
  53711. options.uniforms = options.uniforms || ["worldViewProjection"];
  53712. options.uniformBuffers = options.uniformBuffers || [];
  53713. options.samplers = options.samplers || [];
  53714. options.defines = options.defines || [];
  53715. _this._options = options;
  53716. return _this;
  53717. }
  53718. ShaderMaterial.prototype.getClassName = function () {
  53719. return "ShaderMaterial";
  53720. };
  53721. ShaderMaterial.prototype.needAlphaBlending = function () {
  53722. return this._options.needAlphaBlending;
  53723. };
  53724. ShaderMaterial.prototype.needAlphaTesting = function () {
  53725. return this._options.needAlphaTesting;
  53726. };
  53727. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53728. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53729. this._options.uniforms.push(uniformName);
  53730. }
  53731. };
  53732. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53733. if (this._options.samplers.indexOf(name) === -1) {
  53734. this._options.samplers.push(name);
  53735. }
  53736. this._textures[name] = texture;
  53737. return this;
  53738. };
  53739. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53740. if (this._options.samplers.indexOf(name) === -1) {
  53741. this._options.samplers.push(name);
  53742. }
  53743. this._checkUniform(name);
  53744. this._textureArrays[name] = textures;
  53745. return this;
  53746. };
  53747. ShaderMaterial.prototype.setFloat = function (name, value) {
  53748. this._checkUniform(name);
  53749. this._floats[name] = value;
  53750. return this;
  53751. };
  53752. ShaderMaterial.prototype.setInt = function (name, value) {
  53753. this._checkUniform(name);
  53754. this._ints[name] = value;
  53755. return this;
  53756. };
  53757. ShaderMaterial.prototype.setFloats = function (name, value) {
  53758. this._checkUniform(name);
  53759. this._floatsArrays[name] = value;
  53760. return this;
  53761. };
  53762. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53763. this._checkUniform(name);
  53764. this._colors3[name] = value;
  53765. return this;
  53766. };
  53767. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53768. this._checkUniform(name);
  53769. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53770. color.toArray(arr, arr.length);
  53771. return arr;
  53772. }, []);
  53773. return this;
  53774. };
  53775. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53776. this._checkUniform(name);
  53777. this._colors4[name] = value;
  53778. return this;
  53779. };
  53780. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53781. this._checkUniform(name);
  53782. this._vectors2[name] = value;
  53783. return this;
  53784. };
  53785. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53786. this._checkUniform(name);
  53787. this._vectors3[name] = value;
  53788. return this;
  53789. };
  53790. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53791. this._checkUniform(name);
  53792. this._vectors4[name] = value;
  53793. return this;
  53794. };
  53795. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53796. this._checkUniform(name);
  53797. this._matrices[name] = value;
  53798. return this;
  53799. };
  53800. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53801. this._checkUniform(name);
  53802. this._matrices3x3[name] = value;
  53803. return this;
  53804. };
  53805. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53806. this._checkUniform(name);
  53807. this._matrices2x2[name] = value;
  53808. return this;
  53809. };
  53810. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53811. this._checkUniform(name);
  53812. this._vectors2Arrays[name] = value;
  53813. return this;
  53814. };
  53815. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53816. this._checkUniform(name);
  53817. this._vectors3Arrays[name] = value;
  53818. return this;
  53819. };
  53820. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53821. if (!mesh) {
  53822. return true;
  53823. }
  53824. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53825. return false;
  53826. }
  53827. return false;
  53828. };
  53829. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53830. var scene = this.getScene();
  53831. var engine = scene.getEngine();
  53832. if (!this.checkReadyOnEveryCall) {
  53833. if (this._renderId === scene.getRenderId()) {
  53834. if (this._checkCache(scene, mesh, useInstances)) {
  53835. return true;
  53836. }
  53837. }
  53838. }
  53839. // Instances
  53840. var defines = [];
  53841. var attribs = [];
  53842. var fallbacks = new BABYLON.EffectFallbacks();
  53843. if (useInstances) {
  53844. defines.push("#define INSTANCES");
  53845. }
  53846. for (var index = 0; index < this._options.defines.length; index++) {
  53847. defines.push(this._options.defines[index]);
  53848. }
  53849. for (var index = 0; index < this._options.attributes.length; index++) {
  53850. attribs.push(this._options.attributes[index]);
  53851. }
  53852. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53853. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53854. defines.push("#define VERTEXCOLOR");
  53855. }
  53856. // Bones
  53857. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53860. if (mesh.numBoneInfluencers > 4) {
  53861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53863. }
  53864. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53865. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53866. fallbacks.addCPUSkinningFallback(0, mesh);
  53867. if (this._options.uniforms.indexOf("mBones") === -1) {
  53868. this._options.uniforms.push("mBones");
  53869. }
  53870. }
  53871. else {
  53872. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53873. }
  53874. // Textures
  53875. for (var name in this._textures) {
  53876. if (!this._textures[name].isReady()) {
  53877. return false;
  53878. }
  53879. }
  53880. // Alpha test
  53881. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53882. defines.push("#define ALPHATEST");
  53883. }
  53884. var previousEffect = this._effect;
  53885. var join = defines.join("\n");
  53886. this._effect = engine.createEffect(this._shaderPath, {
  53887. attributes: attribs,
  53888. uniformsNames: this._options.uniforms,
  53889. uniformBuffersNames: this._options.uniformBuffers,
  53890. samplers: this._options.samplers,
  53891. defines: join,
  53892. fallbacks: fallbacks,
  53893. onCompiled: this.onCompiled,
  53894. onError: this.onError
  53895. }, engine);
  53896. if (!this._effect.isReady()) {
  53897. return false;
  53898. }
  53899. if (previousEffect !== this._effect) {
  53900. scene.resetCachedMaterial();
  53901. }
  53902. this._renderId = scene.getRenderId();
  53903. return true;
  53904. };
  53905. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53906. var scene = this.getScene();
  53907. if (!this._effect) {
  53908. return;
  53909. }
  53910. if (this._options.uniforms.indexOf("world") !== -1) {
  53911. this._effect.setMatrix("world", world);
  53912. }
  53913. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53914. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53915. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53916. }
  53917. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53918. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53919. }
  53920. };
  53921. ShaderMaterial.prototype.bind = function (world, mesh) {
  53922. // Std values
  53923. this.bindOnlyWorldMatrix(world);
  53924. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53925. if (this._options.uniforms.indexOf("view") !== -1) {
  53926. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53927. }
  53928. if (this._options.uniforms.indexOf("projection") !== -1) {
  53929. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53930. }
  53931. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53932. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53933. }
  53934. // Bones
  53935. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53936. var name;
  53937. // Texture
  53938. for (name in this._textures) {
  53939. this._effect.setTexture(name, this._textures[name]);
  53940. }
  53941. // Texture arrays
  53942. for (name in this._textureArrays) {
  53943. this._effect.setTextureArray(name, this._textureArrays[name]);
  53944. }
  53945. // Int
  53946. for (name in this._ints) {
  53947. this._effect.setInt(name, this._ints[name]);
  53948. }
  53949. // Float
  53950. for (name in this._floats) {
  53951. this._effect.setFloat(name, this._floats[name]);
  53952. }
  53953. // Floats
  53954. for (name in this._floatsArrays) {
  53955. this._effect.setArray(name, this._floatsArrays[name]);
  53956. }
  53957. // Color3
  53958. for (name in this._colors3) {
  53959. this._effect.setColor3(name, this._colors3[name]);
  53960. }
  53961. for (name in this._colors3Arrays) {
  53962. this._effect.setArray3(name, this._colors3Arrays[name]);
  53963. }
  53964. // Color4
  53965. for (name in this._colors4) {
  53966. var color = this._colors4[name];
  53967. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53968. }
  53969. // Vector2
  53970. for (name in this._vectors2) {
  53971. this._effect.setVector2(name, this._vectors2[name]);
  53972. }
  53973. // Vector3
  53974. for (name in this._vectors3) {
  53975. this._effect.setVector3(name, this._vectors3[name]);
  53976. }
  53977. // Vector4
  53978. for (name in this._vectors4) {
  53979. this._effect.setVector4(name, this._vectors4[name]);
  53980. }
  53981. // Matrix
  53982. for (name in this._matrices) {
  53983. this._effect.setMatrix(name, this._matrices[name]);
  53984. }
  53985. // Matrix 3x3
  53986. for (name in this._matrices3x3) {
  53987. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53988. }
  53989. // Matrix 2x2
  53990. for (name in this._matrices2x2) {
  53991. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53992. }
  53993. // Vector2Array
  53994. for (name in this._vectors2Arrays) {
  53995. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53996. }
  53997. // Vector3Array
  53998. for (name in this._vectors3Arrays) {
  53999. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54000. }
  54001. }
  54002. this._afterBind(mesh);
  54003. };
  54004. ShaderMaterial.prototype.getActiveTextures = function () {
  54005. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54006. for (var name in this._textures) {
  54007. activeTextures.push(this._textures[name]);
  54008. }
  54009. for (var name in this._textureArrays) {
  54010. var array = this._textureArrays[name];
  54011. for (var index = 0; index < array.length; index++) {
  54012. activeTextures.push(array[index]);
  54013. }
  54014. }
  54015. return activeTextures;
  54016. };
  54017. ShaderMaterial.prototype.hasTexture = function (texture) {
  54018. if (_super.prototype.hasTexture.call(this, texture)) {
  54019. return true;
  54020. }
  54021. for (var name in this._textures) {
  54022. if (this._textures[name] === texture) {
  54023. return true;
  54024. }
  54025. }
  54026. for (var name in this._textureArrays) {
  54027. var array = this._textureArrays[name];
  54028. for (var index = 0; index < array.length; index++) {
  54029. if (array[index] === texture) {
  54030. return true;
  54031. }
  54032. }
  54033. }
  54034. return false;
  54035. };
  54036. ShaderMaterial.prototype.clone = function (name) {
  54037. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54038. return newShaderMaterial;
  54039. };
  54040. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54041. if (forceDisposeTextures) {
  54042. var name;
  54043. for (name in this._textures) {
  54044. this._textures[name].dispose();
  54045. }
  54046. for (name in this._textureArrays) {
  54047. var array = this._textureArrays[name];
  54048. for (var index = 0; index < array.length; index++) {
  54049. array[index].dispose();
  54050. }
  54051. }
  54052. }
  54053. this._textures = {};
  54054. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54055. };
  54056. ShaderMaterial.prototype.serialize = function () {
  54057. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54058. serializationObject.customType = "BABYLON.ShaderMaterial";
  54059. serializationObject.options = this._options;
  54060. serializationObject.shaderPath = this._shaderPath;
  54061. var name;
  54062. // Texture
  54063. serializationObject.textures = {};
  54064. for (name in this._textures) {
  54065. serializationObject.textures[name] = this._textures[name].serialize();
  54066. }
  54067. // Texture arrays
  54068. serializationObject.textureArrays = {};
  54069. for (name in this._textureArrays) {
  54070. serializationObject.textureArrays[name] = [];
  54071. var array = this._textureArrays[name];
  54072. for (var index = 0; index < array.length; index++) {
  54073. serializationObject.textureArrays[name].push(array[index].serialize());
  54074. }
  54075. }
  54076. // Float
  54077. serializationObject.floats = {};
  54078. for (name in this._floats) {
  54079. serializationObject.floats[name] = this._floats[name];
  54080. }
  54081. // Float s
  54082. serializationObject.FloatArrays = {};
  54083. for (name in this._floatsArrays) {
  54084. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54085. }
  54086. // Color3
  54087. serializationObject.colors3 = {};
  54088. for (name in this._colors3) {
  54089. serializationObject.colors3[name] = this._colors3[name].asArray();
  54090. }
  54091. // Color3 array
  54092. serializationObject.colors3Arrays = {};
  54093. for (name in this._colors3Arrays) {
  54094. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54095. }
  54096. // Color4
  54097. serializationObject.colors4 = {};
  54098. for (name in this._colors4) {
  54099. serializationObject.colors4[name] = this._colors4[name].asArray();
  54100. }
  54101. // Vector2
  54102. serializationObject.vectors2 = {};
  54103. for (name in this._vectors2) {
  54104. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54105. }
  54106. // Vector3
  54107. serializationObject.vectors3 = {};
  54108. for (name in this._vectors3) {
  54109. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54110. }
  54111. // Vector4
  54112. serializationObject.vectors4 = {};
  54113. for (name in this._vectors4) {
  54114. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54115. }
  54116. // Matrix
  54117. serializationObject.matrices = {};
  54118. for (name in this._matrices) {
  54119. serializationObject.matrices[name] = this._matrices[name].asArray();
  54120. }
  54121. // Matrix 3x3
  54122. serializationObject.matrices3x3 = {};
  54123. for (name in this._matrices3x3) {
  54124. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54125. }
  54126. // Matrix 2x2
  54127. serializationObject.matrices2x2 = {};
  54128. for (name in this._matrices2x2) {
  54129. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54130. }
  54131. // Vector2Array
  54132. serializationObject.vectors2Arrays = {};
  54133. for (name in this._vectors2Arrays) {
  54134. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54135. }
  54136. // Vector3Array
  54137. serializationObject.vectors3Arrays = {};
  54138. for (name in this._vectors3Arrays) {
  54139. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54140. }
  54141. return serializationObject;
  54142. };
  54143. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54144. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54145. var name;
  54146. // Texture
  54147. for (name in source.textures) {
  54148. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54149. }
  54150. // Texture arrays
  54151. for (name in source.textureArrays) {
  54152. var array = source.textureArrays[name];
  54153. var textureArray = new Array();
  54154. for (var index = 0; index < array.length; index++) {
  54155. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54156. }
  54157. material.setTextureArray(name, textureArray);
  54158. }
  54159. // Float
  54160. for (name in source.floats) {
  54161. material.setFloat(name, source.floats[name]);
  54162. }
  54163. // Float s
  54164. for (name in source.floatsArrays) {
  54165. material.setFloats(name, source.floatsArrays[name]);
  54166. }
  54167. // Color3
  54168. for (name in source.colors3) {
  54169. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54170. }
  54171. // Color3 arrays
  54172. for (name in source.colors3Arrays) {
  54173. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54174. if (i % 3 === 0) {
  54175. arr.push([num]);
  54176. }
  54177. else {
  54178. arr[arr.length - 1].push(num);
  54179. }
  54180. return arr;
  54181. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54182. material.setColor3Array(name, colors);
  54183. }
  54184. // Color4
  54185. for (name in source.colors4) {
  54186. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54187. }
  54188. // Vector2
  54189. for (name in source.vectors2) {
  54190. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54191. }
  54192. // Vector3
  54193. for (name in source.vectors3) {
  54194. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54195. }
  54196. // Vector4
  54197. for (name in source.vectors4) {
  54198. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54199. }
  54200. // Matrix
  54201. for (name in source.matrices) {
  54202. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54203. }
  54204. // Matrix 3x3
  54205. for (name in source.matrices3x3) {
  54206. material.setMatrix3x3(name, source.matrices3x3[name]);
  54207. }
  54208. // Matrix 2x2
  54209. for (name in source.matrices2x2) {
  54210. material.setMatrix2x2(name, source.matrices2x2[name]);
  54211. }
  54212. // Vector2Array
  54213. for (name in source.vectors2Arrays) {
  54214. material.setArray2(name, source.vectors2Arrays[name]);
  54215. }
  54216. // Vector3Array
  54217. for (name in source.vectors3Arrays) {
  54218. material.setArray3(name, source.vectors3Arrays[name]);
  54219. }
  54220. return material;
  54221. };
  54222. return ShaderMaterial;
  54223. }(BABYLON.Material));
  54224. BABYLON.ShaderMaterial = ShaderMaterial;
  54225. })(BABYLON || (BABYLON = {}));
  54226. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54227. var BABYLON;
  54228. (function (BABYLON) {
  54229. var GroundMesh = /** @class */ (function (_super) {
  54230. __extends(GroundMesh, _super);
  54231. function GroundMesh(name, scene) {
  54232. var _this = _super.call(this, name, scene) || this;
  54233. _this.generateOctree = false;
  54234. return _this;
  54235. }
  54236. GroundMesh.prototype.getClassName = function () {
  54237. return "GroundMesh";
  54238. };
  54239. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54240. get: function () {
  54241. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54242. },
  54243. enumerable: true,
  54244. configurable: true
  54245. });
  54246. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54247. get: function () {
  54248. return this._subdivisionsX;
  54249. },
  54250. enumerable: true,
  54251. configurable: true
  54252. });
  54253. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54254. get: function () {
  54255. return this._subdivisionsY;
  54256. },
  54257. enumerable: true,
  54258. configurable: true
  54259. });
  54260. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54261. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54262. this._subdivisionsX = chunksCount;
  54263. this._subdivisionsY = chunksCount;
  54264. this.subdivide(chunksCount);
  54265. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54266. };
  54267. /**
  54268. * Returns a height (y) value in the Worl system :
  54269. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54270. * Returns the ground y position if (x, z) are outside the ground surface.
  54271. */
  54272. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54273. var world = this.getWorldMatrix();
  54274. var invMat = BABYLON.Tmp.Matrix[5];
  54275. world.invertToRef(invMat);
  54276. var tmpVect = BABYLON.Tmp.Vector3[8];
  54277. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54278. x = tmpVect.x;
  54279. z = tmpVect.z;
  54280. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54281. return this.position.y;
  54282. }
  54283. if (!this._heightQuads || this._heightQuads.length == 0) {
  54284. this._initHeightQuads();
  54285. this._computeHeightQuads();
  54286. }
  54287. var facet = this._getFacetAt(x, z);
  54288. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54289. // return y in the World system
  54290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54291. return tmpVect.y;
  54292. };
  54293. /**
  54294. * Returns a normalized vector (Vector3) orthogonal to the ground
  54295. * at the ground coordinates (x, z) expressed in the World system.
  54296. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54297. */
  54298. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54299. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54300. this.getNormalAtCoordinatesToRef(x, z, normal);
  54301. return normal;
  54302. };
  54303. /**
  54304. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54305. * at the ground coordinates (x, z) expressed in the World system.
  54306. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54307. * Returns the GroundMesh.
  54308. */
  54309. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54310. var world = this.getWorldMatrix();
  54311. var tmpMat = BABYLON.Tmp.Matrix[5];
  54312. world.invertToRef(tmpMat);
  54313. var tmpVect = BABYLON.Tmp.Vector3[8];
  54314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54315. x = tmpVect.x;
  54316. z = tmpVect.z;
  54317. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54318. return this;
  54319. }
  54320. if (!this._heightQuads || this._heightQuads.length == 0) {
  54321. this._initHeightQuads();
  54322. this._computeHeightQuads();
  54323. }
  54324. var facet = this._getFacetAt(x, z);
  54325. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54326. return this;
  54327. };
  54328. /**
  54329. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54330. * if the ground has been updated.
  54331. * This can be used in the render loop.
  54332. * Returns the GroundMesh.
  54333. */
  54334. GroundMesh.prototype.updateCoordinateHeights = function () {
  54335. if (!this._heightQuads || this._heightQuads.length == 0) {
  54336. this._initHeightQuads();
  54337. }
  54338. this._computeHeightQuads();
  54339. return this;
  54340. };
  54341. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54342. GroundMesh.prototype._getFacetAt = function (x, z) {
  54343. // retrieve col and row from x, z coordinates in the ground local system
  54344. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54345. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54346. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54347. var facet;
  54348. if (z < quad.slope.x * x + quad.slope.y) {
  54349. facet = quad.facet1;
  54350. }
  54351. else {
  54352. facet = quad.facet2;
  54353. }
  54354. return facet;
  54355. };
  54356. // Creates and populates the heightMap array with "facet" elements :
  54357. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54358. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54359. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54360. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54361. // Returns the GroundMesh.
  54362. GroundMesh.prototype._initHeightQuads = function () {
  54363. var subdivisionsX = this._subdivisionsX;
  54364. var subdivisionsY = this._subdivisionsY;
  54365. this._heightQuads = new Array();
  54366. for (var row = 0; row < subdivisionsY; row++) {
  54367. for (var col = 0; col < subdivisionsX; col++) {
  54368. 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) };
  54369. this._heightQuads[row * subdivisionsX + col] = quad;
  54370. }
  54371. }
  54372. return this;
  54373. };
  54374. // Compute each quad element values and update the the heightMap array :
  54375. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54376. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54377. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54378. // Returns the GroundMesh.
  54379. GroundMesh.prototype._computeHeightQuads = function () {
  54380. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54381. if (!positions) {
  54382. return this;
  54383. }
  54384. var v1 = BABYLON.Tmp.Vector3[3];
  54385. var v2 = BABYLON.Tmp.Vector3[2];
  54386. var v3 = BABYLON.Tmp.Vector3[1];
  54387. var v4 = BABYLON.Tmp.Vector3[0];
  54388. var v1v2 = BABYLON.Tmp.Vector3[4];
  54389. var v1v3 = BABYLON.Tmp.Vector3[5];
  54390. var v1v4 = BABYLON.Tmp.Vector3[6];
  54391. var norm1 = BABYLON.Tmp.Vector3[7];
  54392. var norm2 = BABYLON.Tmp.Vector3[8];
  54393. var i = 0;
  54394. var j = 0;
  54395. var k = 0;
  54396. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54397. var h = 0;
  54398. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54399. var d2 = 0;
  54400. var subdivisionsX = this._subdivisionsX;
  54401. var subdivisionsY = this._subdivisionsY;
  54402. for (var row = 0; row < subdivisionsY; row++) {
  54403. for (var col = 0; col < subdivisionsX; col++) {
  54404. i = col * 3;
  54405. j = row * (subdivisionsX + 1) * 3;
  54406. k = (row + 1) * (subdivisionsX + 1) * 3;
  54407. v1.x = positions[j + i];
  54408. v1.y = positions[j + i + 1];
  54409. v1.z = positions[j + i + 2];
  54410. v2.x = positions[j + i + 3];
  54411. v2.y = positions[j + i + 4];
  54412. v2.z = positions[j + i + 5];
  54413. v3.x = positions[k + i];
  54414. v3.y = positions[k + i + 1];
  54415. v3.z = positions[k + i + 2];
  54416. v4.x = positions[k + i + 3];
  54417. v4.y = positions[k + i + 4];
  54418. v4.z = positions[k + i + 5];
  54419. // 2D slope V1V4
  54420. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54421. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54422. // facet equations :
  54423. // we compute each facet normal vector
  54424. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54425. // we compute the value d by applying the equation to v1 which belongs to the plane
  54426. // then we store the facet equation in a Vector4
  54427. v2.subtractToRef(v1, v1v2);
  54428. v3.subtractToRef(v1, v1v3);
  54429. v4.subtractToRef(v1, v1v4);
  54430. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54431. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54432. norm1.normalize();
  54433. norm2.normalize();
  54434. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54435. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54436. var quad = this._heightQuads[row * subdivisionsX + col];
  54437. quad.slope.copyFromFloats(cd, h);
  54438. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54439. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54440. }
  54441. }
  54442. return this;
  54443. };
  54444. GroundMesh.prototype.serialize = function (serializationObject) {
  54445. _super.prototype.serialize.call(this, serializationObject);
  54446. serializationObject.subdivisionsX = this._subdivisionsX;
  54447. serializationObject.subdivisionsY = this._subdivisionsY;
  54448. serializationObject.minX = this._minX;
  54449. serializationObject.maxX = this._maxX;
  54450. serializationObject.minZ = this._minZ;
  54451. serializationObject.maxZ = this._maxZ;
  54452. serializationObject.width = this._width;
  54453. serializationObject.height = this._height;
  54454. };
  54455. GroundMesh.Parse = function (parsedMesh, scene) {
  54456. var result = new GroundMesh(parsedMesh.name, scene);
  54457. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54458. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54459. result._minX = parsedMesh.minX;
  54460. result._maxX = parsedMesh.maxX;
  54461. result._minZ = parsedMesh.minZ;
  54462. result._maxZ = parsedMesh.maxZ;
  54463. result._width = parsedMesh.width;
  54464. result._height = parsedMesh.height;
  54465. return result;
  54466. };
  54467. return GroundMesh;
  54468. }(BABYLON.Mesh));
  54469. BABYLON.GroundMesh = GroundMesh;
  54470. })(BABYLON || (BABYLON = {}));
  54471. //# sourceMappingURL=babylon.groundMesh.js.map
  54472. var BABYLON;
  54473. (function (BABYLON) {
  54474. /**
  54475. * Creates an instance based on a source mesh.
  54476. */
  54477. var InstancedMesh = /** @class */ (function (_super) {
  54478. __extends(InstancedMesh, _super);
  54479. function InstancedMesh(name, source) {
  54480. var _this = _super.call(this, name, source.getScene()) || this;
  54481. source.instances.push(_this);
  54482. _this._sourceMesh = source;
  54483. _this.position.copyFrom(source.position);
  54484. _this.rotation.copyFrom(source.rotation);
  54485. _this.scaling.copyFrom(source.scaling);
  54486. if (source.rotationQuaternion) {
  54487. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54488. }
  54489. _this.infiniteDistance = source.infiniteDistance;
  54490. _this.setPivotMatrix(source.getPivotMatrix());
  54491. _this.refreshBoundingInfo();
  54492. _this._syncSubMeshes();
  54493. return _this;
  54494. }
  54495. /**
  54496. * Returns the string "InstancedMesh".
  54497. */
  54498. InstancedMesh.prototype.getClassName = function () {
  54499. return "InstancedMesh";
  54500. };
  54501. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54502. // Methods
  54503. get: function () {
  54504. return this._sourceMesh.receiveShadows;
  54505. },
  54506. enumerable: true,
  54507. configurable: true
  54508. });
  54509. Object.defineProperty(InstancedMesh.prototype, "material", {
  54510. get: function () {
  54511. return this._sourceMesh.material;
  54512. },
  54513. enumerable: true,
  54514. configurable: true
  54515. });
  54516. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54517. get: function () {
  54518. return this._sourceMesh.visibility;
  54519. },
  54520. enumerable: true,
  54521. configurable: true
  54522. });
  54523. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54524. get: function () {
  54525. return this._sourceMesh.skeleton;
  54526. },
  54527. enumerable: true,
  54528. configurable: true
  54529. });
  54530. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54531. get: function () {
  54532. return this._sourceMesh.renderingGroupId;
  54533. },
  54534. set: function (value) {
  54535. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  54536. return;
  54537. }
  54538. //no-op with warning
  54539. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  54540. },
  54541. enumerable: true,
  54542. configurable: true
  54543. });
  54544. /**
  54545. * Returns the total number of vertices (integer).
  54546. */
  54547. InstancedMesh.prototype.getTotalVertices = function () {
  54548. return this._sourceMesh.getTotalVertices();
  54549. };
  54550. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54551. get: function () {
  54552. return this._sourceMesh;
  54553. },
  54554. enumerable: true,
  54555. configurable: true
  54556. });
  54557. /**
  54558. * Is this node ready to be used/rendered
  54559. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54560. * @return {boolean} is it ready
  54561. */
  54562. InstancedMesh.prototype.isReady = function (completeCheck) {
  54563. if (completeCheck === void 0) { completeCheck = false; }
  54564. return this._sourceMesh.isReady(completeCheck, true);
  54565. };
  54566. /**
  54567. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54568. */
  54569. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54570. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54571. };
  54572. /**
  54573. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54574. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54575. * The `data` are either a numeric array either a Float32Array.
  54576. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54577. * 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).
  54578. * Note that a new underlying VertexBuffer object is created each call.
  54579. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54580. *
  54581. * Possible `kind` values :
  54582. * - BABYLON.VertexBuffer.PositionKind
  54583. * - BABYLON.VertexBuffer.UVKind
  54584. * - BABYLON.VertexBuffer.UV2Kind
  54585. * - BABYLON.VertexBuffer.UV3Kind
  54586. * - BABYLON.VertexBuffer.UV4Kind
  54587. * - BABYLON.VertexBuffer.UV5Kind
  54588. * - BABYLON.VertexBuffer.UV6Kind
  54589. * - BABYLON.VertexBuffer.ColorKind
  54590. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54591. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54592. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54593. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54594. *
  54595. * Returns the Mesh.
  54596. */
  54597. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54598. if (this.sourceMesh) {
  54599. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54600. }
  54601. return this.sourceMesh;
  54602. };
  54603. /**
  54604. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54605. * If the mesh has no geometry, it is simply returned as it is.
  54606. * The `data` are either a numeric array either a Float32Array.
  54607. * No new underlying VertexBuffer object is created.
  54608. * 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.
  54609. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54610. *
  54611. * Possible `kind` values :
  54612. * - BABYLON.VertexBuffer.PositionKind
  54613. * - BABYLON.VertexBuffer.UVKind
  54614. * - BABYLON.VertexBuffer.UV2Kind
  54615. * - BABYLON.VertexBuffer.UV3Kind
  54616. * - BABYLON.VertexBuffer.UV4Kind
  54617. * - BABYLON.VertexBuffer.UV5Kind
  54618. * - BABYLON.VertexBuffer.UV6Kind
  54619. * - BABYLON.VertexBuffer.ColorKind
  54620. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54621. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54622. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54623. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54624. *
  54625. * Returns the Mesh.
  54626. */
  54627. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54628. if (this.sourceMesh) {
  54629. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54630. }
  54631. return this.sourceMesh;
  54632. };
  54633. /**
  54634. * Sets the mesh indices.
  54635. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54636. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54637. * This method creates a new index buffer each call.
  54638. * Returns the Mesh.
  54639. */
  54640. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54641. if (totalVertices === void 0) { totalVertices = null; }
  54642. if (this.sourceMesh) {
  54643. this.sourceMesh.setIndices(indices, totalVertices);
  54644. }
  54645. return this.sourceMesh;
  54646. };
  54647. /**
  54648. * Boolean : True if the mesh owns the requested kind of data.
  54649. */
  54650. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54651. return this._sourceMesh.isVerticesDataPresent(kind);
  54652. };
  54653. /**
  54654. * Returns an array of indices (IndicesArray).
  54655. */
  54656. InstancedMesh.prototype.getIndices = function () {
  54657. return this._sourceMesh.getIndices();
  54658. };
  54659. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54660. get: function () {
  54661. return this._sourceMesh._positions;
  54662. },
  54663. enumerable: true,
  54664. configurable: true
  54665. });
  54666. /**
  54667. * Sets a new updated BoundingInfo to the mesh.
  54668. * Returns the mesh.
  54669. */
  54670. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54671. var meshBB = this._sourceMesh.getBoundingInfo();
  54672. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54673. this._updateBoundingInfo();
  54674. return this;
  54675. };
  54676. InstancedMesh.prototype._preActivate = function () {
  54677. if (this._currentLOD) {
  54678. this._currentLOD._preActivate();
  54679. }
  54680. return this;
  54681. };
  54682. InstancedMesh.prototype._activate = function (renderId) {
  54683. if (this._currentLOD) {
  54684. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54685. }
  54686. return this;
  54687. };
  54688. /**
  54689. * Returns the current associated LOD AbstractMesh.
  54690. */
  54691. InstancedMesh.prototype.getLOD = function (camera) {
  54692. if (!camera) {
  54693. return this;
  54694. }
  54695. var boundingInfo = this.getBoundingInfo();
  54696. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54697. if (this._currentLOD === this.sourceMesh) {
  54698. return this;
  54699. }
  54700. return this._currentLOD;
  54701. };
  54702. InstancedMesh.prototype._syncSubMeshes = function () {
  54703. this.releaseSubMeshes();
  54704. if (this._sourceMesh.subMeshes) {
  54705. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54706. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54707. }
  54708. }
  54709. return this;
  54710. };
  54711. InstancedMesh.prototype._generatePointsArray = function () {
  54712. return this._sourceMesh._generatePointsArray();
  54713. };
  54714. /**
  54715. * Creates a new InstancedMesh from the current mesh.
  54716. * - name (string) : the cloned mesh name
  54717. * - newParent (optional Node) : the optional Node to parent the clone to.
  54718. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54719. *
  54720. * Returns the clone.
  54721. */
  54722. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54723. var result = this._sourceMesh.createInstance(name);
  54724. // Deep copy
  54725. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54726. // Bounding info
  54727. this.refreshBoundingInfo();
  54728. // Parent
  54729. if (newParent) {
  54730. result.parent = newParent;
  54731. }
  54732. if (!doNotCloneChildren) {
  54733. // Children
  54734. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54735. var mesh = this.getScene().meshes[index];
  54736. if (mesh.parent === this) {
  54737. mesh.clone(mesh.name, result);
  54738. }
  54739. }
  54740. }
  54741. result.computeWorldMatrix(true);
  54742. return result;
  54743. };
  54744. /**
  54745. * Disposes the InstancedMesh.
  54746. * Returns nothing.
  54747. */
  54748. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  54749. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  54750. // Remove from mesh
  54751. var index = this._sourceMesh.instances.indexOf(this);
  54752. this._sourceMesh.instances.splice(index, 1);
  54753. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  54754. };
  54755. return InstancedMesh;
  54756. }(BABYLON.AbstractMesh));
  54757. BABYLON.InstancedMesh = InstancedMesh;
  54758. })(BABYLON || (BABYLON = {}));
  54759. //# sourceMappingURL=babylon.instancedMesh.js.map
  54760. var BABYLON;
  54761. (function (BABYLON) {
  54762. var LinesMesh = /** @class */ (function (_super) {
  54763. __extends(LinesMesh, _super);
  54764. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54765. if (scene === void 0) { scene = null; }
  54766. if (parent === void 0) { parent = null; }
  54767. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54768. _this.useVertexColor = useVertexColor;
  54769. _this.useVertexAlpha = useVertexAlpha;
  54770. _this.color = new BABYLON.Color3(1, 1, 1);
  54771. _this.alpha = 1;
  54772. if (source) {
  54773. _this.color = source.color.clone();
  54774. _this.alpha = source.alpha;
  54775. _this.useVertexColor = source.useVertexColor;
  54776. _this.useVertexAlpha = source.useVertexAlpha;
  54777. }
  54778. _this._intersectionThreshold = 0.1;
  54779. var defines = [];
  54780. var options = {
  54781. attributes: [BABYLON.VertexBuffer.PositionKind],
  54782. uniforms: ["world", "viewProjection"],
  54783. needAlphaBlending: true,
  54784. defines: defines
  54785. };
  54786. if (useVertexAlpha === false) {
  54787. options.needAlphaBlending = false;
  54788. }
  54789. if (!useVertexColor) {
  54790. options.uniforms.push("color");
  54791. }
  54792. else {
  54793. options.defines.push("#define VERTEXCOLOR");
  54794. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54795. }
  54796. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54797. return _this;
  54798. }
  54799. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54800. /**
  54801. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54802. * This margin is expressed in world space coordinates, so its value may vary.
  54803. * Default value is 0.1
  54804. * @returns the intersection Threshold value.
  54805. */
  54806. get: function () {
  54807. return this._intersectionThreshold;
  54808. },
  54809. /**
  54810. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54811. * This margin is expressed in world space coordinates, so its value may vary.
  54812. * @param value the new threshold to apply
  54813. */
  54814. set: function (value) {
  54815. if (this._intersectionThreshold === value) {
  54816. return;
  54817. }
  54818. this._intersectionThreshold = value;
  54819. if (this.geometry) {
  54820. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54821. }
  54822. },
  54823. enumerable: true,
  54824. configurable: true
  54825. });
  54826. /**
  54827. * Returns the string "LineMesh"
  54828. */
  54829. LinesMesh.prototype.getClassName = function () {
  54830. return "LinesMesh";
  54831. };
  54832. Object.defineProperty(LinesMesh.prototype, "material", {
  54833. get: function () {
  54834. return this._colorShader;
  54835. },
  54836. set: function (value) {
  54837. // Do nothing
  54838. },
  54839. enumerable: true,
  54840. configurable: true
  54841. });
  54842. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54843. get: function () {
  54844. return false;
  54845. },
  54846. enumerable: true,
  54847. configurable: true
  54848. });
  54849. LinesMesh.prototype.createInstance = function (name) {
  54850. throw new Error("LinesMeshes do not support createInstance.");
  54851. };
  54852. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54853. if (!this._geometry) {
  54854. return this;
  54855. }
  54856. // VBOs
  54857. this._geometry._bind(this._colorShader.getEffect());
  54858. // Color
  54859. if (!this.useVertexColor) {
  54860. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54861. }
  54862. return this;
  54863. };
  54864. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54865. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54866. return this;
  54867. }
  54868. var engine = this.getScene().getEngine();
  54869. // Draw order
  54870. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54871. return this;
  54872. };
  54873. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54874. this._colorShader.dispose();
  54875. _super.prototype.dispose.call(this, doNotRecurse);
  54876. };
  54877. /**
  54878. * Returns a new LineMesh object cloned from the current one.
  54879. */
  54880. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54881. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54882. };
  54883. return LinesMesh;
  54884. }(BABYLON.Mesh));
  54885. BABYLON.LinesMesh = LinesMesh;
  54886. })(BABYLON || (BABYLON = {}));
  54887. //# sourceMappingURL=babylon.linesMesh.js.map
  54888. var BABYLON;
  54889. (function (BABYLON) {
  54890. var MeshBuilder = /** @class */ (function () {
  54891. function MeshBuilder() {
  54892. }
  54893. MeshBuilder.updateSideOrientation = function (orientation) {
  54894. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54895. return BABYLON.Mesh.DOUBLESIDE;
  54896. }
  54897. if (orientation === undefined || orientation === null) {
  54898. return BABYLON.Mesh.FRONTSIDE;
  54899. }
  54900. return orientation;
  54901. };
  54902. /**
  54903. * Creates a box mesh.
  54904. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54905. * The parameter `size` sets the size (float) of each box side (default 1).
  54906. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54907. * 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).
  54908. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54909. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54910. * 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).
  54911. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54913. */
  54914. MeshBuilder.CreateBox = function (name, options, scene) {
  54915. if (scene === void 0) { scene = null; }
  54916. var box = new BABYLON.Mesh(name, scene);
  54917. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54918. box._originalBuilderSideOrientation = options.sideOrientation;
  54919. var vertexData = BABYLON.VertexData.CreateBox(options);
  54920. vertexData.applyToMesh(box, options.updatable);
  54921. return box;
  54922. };
  54923. /**
  54924. * Creates a sphere mesh.
  54925. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54926. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54927. * 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`).
  54928. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54929. * 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
  54930. * 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).
  54931. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54932. * 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).
  54933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54935. */
  54936. MeshBuilder.CreateSphere = function (name, options, scene) {
  54937. var sphere = new BABYLON.Mesh(name, scene);
  54938. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54939. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54940. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54941. vertexData.applyToMesh(sphere, options.updatable);
  54942. return sphere;
  54943. };
  54944. /**
  54945. * Creates a plane polygonal mesh. By default, this is a disc.
  54946. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54947. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54948. * 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.
  54949. * 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
  54950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54951. * 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).
  54952. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54953. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54954. */
  54955. MeshBuilder.CreateDisc = function (name, options, scene) {
  54956. if (scene === void 0) { scene = null; }
  54957. var disc = new BABYLON.Mesh(name, scene);
  54958. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54959. disc._originalBuilderSideOrientation = options.sideOrientation;
  54960. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54961. vertexData.applyToMesh(disc, options.updatable);
  54962. return disc;
  54963. };
  54964. /**
  54965. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54966. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54967. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54968. * 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`).
  54969. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54970. * 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.
  54971. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54972. * 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).
  54973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54975. */
  54976. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54977. var sphere = new BABYLON.Mesh(name, scene);
  54978. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54979. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54980. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54981. vertexData.applyToMesh(sphere, options.updatable);
  54982. return sphere;
  54983. };
  54984. ;
  54985. /**
  54986. * Creates a ribbon mesh.
  54987. * 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.
  54988. *
  54989. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54990. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54991. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54992. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54993. * 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.
  54994. * 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.
  54995. * 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
  54996. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54997. * 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).
  54998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54999. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55000. * 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.
  55001. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55002. * 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
  55003. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55004. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55006. */
  55007. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55008. if (scene === void 0) { scene = null; }
  55009. var pathArray = options.pathArray;
  55010. var closeArray = options.closeArray;
  55011. var closePath = options.closePath;
  55012. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55013. var instance = options.instance;
  55014. var updatable = options.updatable;
  55015. if (instance) {
  55016. // positionFunction : ribbon case
  55017. // only pathArray and sideOrientation parameters are taken into account for positions update
  55018. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55019. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55020. var positionFunction = function (positions) {
  55021. var minlg = pathArray[0].length;
  55022. var i = 0;
  55023. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55024. for (var si = 1; si <= ns; si++) {
  55025. for (var p = 0; p < pathArray.length; p++) {
  55026. var path = pathArray[p];
  55027. var l = path.length;
  55028. minlg = (minlg < l) ? minlg : l;
  55029. var j = 0;
  55030. while (j < minlg) {
  55031. positions[i] = path[j].x;
  55032. positions[i + 1] = path[j].y;
  55033. positions[i + 2] = path[j].z;
  55034. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55035. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55036. }
  55037. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55038. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55039. }
  55040. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55041. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55042. }
  55043. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55044. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55045. }
  55046. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55047. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55048. }
  55049. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55050. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55051. }
  55052. j++;
  55053. i += 3;
  55054. }
  55055. if (instance._closePath) {
  55056. positions[i] = path[0].x;
  55057. positions[i + 1] = path[0].y;
  55058. positions[i + 2] = path[0].z;
  55059. i += 3;
  55060. }
  55061. }
  55062. }
  55063. };
  55064. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55065. positionFunction(positions);
  55066. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55067. instance._boundingInfo.update(instance._worldMatrix);
  55068. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55069. if (options.colors) {
  55070. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55071. for (var c = 0; c < options.colors.length; c++) {
  55072. colors[c * 4] = options.colors[c].r;
  55073. colors[c * 4 + 1] = options.colors[c].g;
  55074. colors[c * 4 + 2] = options.colors[c].b;
  55075. colors[c * 4 + 3] = options.colors[c].a;
  55076. }
  55077. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55078. }
  55079. if (options.uvs) {
  55080. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55081. for (var i = 0; i < options.uvs.length; i++) {
  55082. uvs[i * 2] = options.uvs[i].x;
  55083. uvs[i * 2 + 1] = options.uvs[i].y;
  55084. }
  55085. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55086. }
  55087. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55088. var indices = instance.getIndices();
  55089. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55090. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55091. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55092. if (instance._closePath) {
  55093. var indexFirst = 0;
  55094. var indexLast = 0;
  55095. for (var p = 0; p < pathArray.length; p++) {
  55096. indexFirst = instance._idx[p] * 3;
  55097. if (p + 1 < pathArray.length) {
  55098. indexLast = (instance._idx[p + 1] - 1) * 3;
  55099. }
  55100. else {
  55101. indexLast = normals.length - 3;
  55102. }
  55103. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55104. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55105. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55106. normals[indexLast] = normals[indexFirst];
  55107. normals[indexLast + 1] = normals[indexFirst + 1];
  55108. normals[indexLast + 2] = normals[indexFirst + 2];
  55109. }
  55110. }
  55111. if (!(instance.areNormalsFrozen)) {
  55112. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55113. }
  55114. }
  55115. return instance;
  55116. }
  55117. else {
  55118. var ribbon = new BABYLON.Mesh(name, scene);
  55119. ribbon._originalBuilderSideOrientation = sideOrientation;
  55120. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55121. if (closePath) {
  55122. ribbon._idx = vertexData._idx;
  55123. }
  55124. ribbon._closePath = closePath;
  55125. ribbon._closeArray = closeArray;
  55126. vertexData.applyToMesh(ribbon, updatable);
  55127. return ribbon;
  55128. }
  55129. };
  55130. /**
  55131. * Creates a cylinder or a cone mesh.
  55132. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55133. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55134. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55135. * 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.
  55136. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55137. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55138. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55139. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55140. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55141. * 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).
  55142. * 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
  55143. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55144. * 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
  55145. * 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.
  55146. * If `enclose` is false, a ring surface is one element.
  55147. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55148. * 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
  55149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55150. * 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).
  55151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55153. */
  55154. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55155. var cylinder = new BABYLON.Mesh(name, scene);
  55156. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55157. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55158. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55159. vertexData.applyToMesh(cylinder, options.updatable);
  55160. return cylinder;
  55161. };
  55162. /**
  55163. * Creates a torus mesh.
  55164. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55165. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55166. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55167. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55169. * 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).
  55170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55172. */
  55173. MeshBuilder.CreateTorus = function (name, options, scene) {
  55174. var torus = new BABYLON.Mesh(name, scene);
  55175. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55176. torus._originalBuilderSideOrientation = options.sideOrientation;
  55177. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55178. vertexData.applyToMesh(torus, options.updatable);
  55179. return torus;
  55180. };
  55181. /**
  55182. * Creates a torus knot mesh.
  55183. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55184. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55185. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55186. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55187. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55188. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55189. * 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).
  55190. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55192. */
  55193. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55194. var torusKnot = new BABYLON.Mesh(name, scene);
  55195. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55196. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55197. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55198. vertexData.applyToMesh(torusKnot, options.updatable);
  55199. return torusKnot;
  55200. };
  55201. /**
  55202. * Creates a line system mesh.
  55203. * A line system is a pool of many lines gathered in a single mesh.
  55204. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55205. * 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.
  55206. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55207. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55208. * 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
  55209. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55210. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55211. * 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
  55212. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55214. */
  55215. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55216. var instance = options.instance;
  55217. var lines = options.lines;
  55218. var colors = options.colors;
  55219. if (instance) {
  55220. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55221. var vertexColor;
  55222. var lineColors;
  55223. if (colors) {
  55224. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55225. }
  55226. var i = 0;
  55227. var c = 0;
  55228. for (var l = 0; l < lines.length; l++) {
  55229. var points = lines[l];
  55230. for (var p = 0; p < points.length; p++) {
  55231. positions[i] = points[p].x;
  55232. positions[i + 1] = points[p].y;
  55233. positions[i + 2] = points[p].z;
  55234. if (colors && vertexColor) {
  55235. lineColors = colors[l];
  55236. vertexColor[c] = lineColors[p].r;
  55237. vertexColor[c + 1] = lineColors[p].g;
  55238. vertexColor[c + 2] = lineColors[p].b;
  55239. vertexColor[c + 3] = lineColors[p].a;
  55240. c += 4;
  55241. }
  55242. i += 3;
  55243. }
  55244. }
  55245. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55246. if (colors && vertexColor) {
  55247. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55248. }
  55249. return instance;
  55250. }
  55251. // line system creation
  55252. var useVertexColor = (colors) ? true : false;
  55253. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55254. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55255. vertexData.applyToMesh(lineSystem, options.updatable);
  55256. return lineSystem;
  55257. };
  55258. /**
  55259. * Creates a line mesh.
  55260. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55261. * 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.
  55262. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55263. * The parameter `points` is an array successive Vector3.
  55264. * 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
  55265. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55266. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55267. * When updating an instance, remember that only point positions can change, not the number of points.
  55268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55269. */
  55270. MeshBuilder.CreateLines = function (name, options, scene) {
  55271. if (scene === void 0) { scene = null; }
  55272. var colors = (options.colors) ? [options.colors] : null;
  55273. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55274. return lines;
  55275. };
  55276. /**
  55277. * Creates a dashed line mesh.
  55278. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55279. * 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.
  55280. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55281. * The parameter `points` is an array successive Vector3.
  55282. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55283. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55284. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55285. * 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
  55286. * When updating an instance, remember that only point positions can change, not the number of points.
  55287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55288. */
  55289. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55290. if (scene === void 0) { scene = null; }
  55291. var points = options.points;
  55292. var instance = options.instance;
  55293. var gapSize = options.gapSize || 1;
  55294. var dashSize = options.dashSize || 3;
  55295. if (instance) {
  55296. var positionFunction = function (positions) {
  55297. var curvect = BABYLON.Vector3.Zero();
  55298. var nbSeg = positions.length / 6;
  55299. var lg = 0;
  55300. var nb = 0;
  55301. var shft = 0;
  55302. var dashshft = 0;
  55303. var curshft = 0;
  55304. var p = 0;
  55305. var i = 0;
  55306. var j = 0;
  55307. for (i = 0; i < points.length - 1; i++) {
  55308. points[i + 1].subtractToRef(points[i], curvect);
  55309. lg += curvect.length();
  55310. }
  55311. shft = lg / nbSeg;
  55312. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55313. for (i = 0; i < points.length - 1; i++) {
  55314. points[i + 1].subtractToRef(points[i], curvect);
  55315. nb = Math.floor(curvect.length() / shft);
  55316. curvect.normalize();
  55317. j = 0;
  55318. while (j < nb && p < positions.length) {
  55319. curshft = shft * j;
  55320. positions[p] = points[i].x + curshft * curvect.x;
  55321. positions[p + 1] = points[i].y + curshft * curvect.y;
  55322. positions[p + 2] = points[i].z + curshft * curvect.z;
  55323. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55324. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55325. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55326. p += 6;
  55327. j++;
  55328. }
  55329. }
  55330. while (p < positions.length) {
  55331. positions[p] = points[i].x;
  55332. positions[p + 1] = points[i].y;
  55333. positions[p + 2] = points[i].z;
  55334. p += 3;
  55335. }
  55336. };
  55337. instance.updateMeshPositions(positionFunction, false);
  55338. return instance;
  55339. }
  55340. // dashed lines creation
  55341. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55342. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55343. vertexData.applyToMesh(dashedLines, options.updatable);
  55344. dashedLines.dashSize = dashSize;
  55345. dashedLines.gapSize = gapSize;
  55346. return dashedLines;
  55347. };
  55348. /**
  55349. * Creates an extruded shape mesh.
  55350. * 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.
  55351. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55352. *
  55353. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55354. * 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
  55355. * extruded along the Z axis.
  55356. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55357. * 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.
  55358. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55359. * 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
  55360. * 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
  55361. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55362. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55363. * 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).
  55364. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55365. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55367. */
  55368. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55369. if (scene === void 0) { scene = null; }
  55370. var path = options.path;
  55371. var shape = options.shape;
  55372. var scale = options.scale || 1;
  55373. var rotation = options.rotation || 0;
  55374. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55375. var updatable = options.updatable;
  55376. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55377. var instance = options.instance || null;
  55378. var invertUV = options.invertUV || false;
  55379. 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);
  55380. };
  55381. /**
  55382. * Creates an custom extruded shape mesh.
  55383. * 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.
  55384. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55385. *
  55386. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55387. * 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
  55388. * extruded along the Z axis.
  55389. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55390. * 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
  55391. * and the distance of this point from the begining of the path :
  55392. * ```javascript
  55393. * var rotationFunction = function(i, distance) {
  55394. * // do things
  55395. * return rotationValue; }
  55396. * ```
  55397. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55398. * 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
  55399. * and the distance of this point from the begining of the path :
  55400. * ```javascript
  55401. * var scaleFunction = function(i, distance) {
  55402. * // do things
  55403. * return scaleValue;}
  55404. * ```
  55405. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55406. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55407. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55408. * 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
  55409. * 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
  55410. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  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.ExtrudeShapeCustom = function (name, options, scene) {
  55418. var path = options.path;
  55419. var shape = options.shape;
  55420. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55421. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55422. var ribbonCloseArray = options.ribbonCloseArray || false;
  55423. var ribbonClosePath = options.ribbonClosePath || false;
  55424. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55425. var updatable = options.updatable;
  55426. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55427. var instance = options.instance;
  55428. var invertUV = options.invertUV || false;
  55429. 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);
  55430. };
  55431. /**
  55432. * Creates lathe mesh.
  55433. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55434. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55435. *
  55436. * 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
  55437. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55438. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55439. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55440. * 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.
  55441. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55442. * 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
  55443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55444. * 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).
  55445. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55446. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55447. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55448. */
  55449. MeshBuilder.CreateLathe = function (name, options, scene) {
  55450. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55451. var closed = (options.closed === undefined) ? true : options.closed;
  55452. var shape = options.shape;
  55453. var radius = options.radius || 1;
  55454. var tessellation = options.tessellation || 64;
  55455. var updatable = options.updatable;
  55456. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55457. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55458. var pi2 = Math.PI * 2;
  55459. var paths = new Array();
  55460. var invertUV = options.invertUV || false;
  55461. var i = 0;
  55462. var p = 0;
  55463. var step = pi2 / tessellation * arc;
  55464. var rotated;
  55465. var path = new Array();
  55466. ;
  55467. for (i = 0; i <= tessellation; i++) {
  55468. var path = [];
  55469. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55470. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55471. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55472. }
  55473. for (p = 0; p < shape.length; p++) {
  55474. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55475. path.push(rotated);
  55476. }
  55477. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55478. 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));
  55479. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55480. }
  55481. paths.push(path);
  55482. }
  55483. // lathe ribbon
  55484. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55485. return lathe;
  55486. };
  55487. /**
  55488. * Creates a plane mesh.
  55489. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55490. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55491. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55492. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55494. * 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).
  55495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55497. */
  55498. MeshBuilder.CreatePlane = function (name, options, scene) {
  55499. var plane = new BABYLON.Mesh(name, scene);
  55500. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55501. plane._originalBuilderSideOrientation = options.sideOrientation;
  55502. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55503. vertexData.applyToMesh(plane, options.updatable);
  55504. if (options.sourcePlane) {
  55505. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55506. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55507. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55508. plane.rotate(vectorProduct, product);
  55509. }
  55510. return plane;
  55511. };
  55512. /**
  55513. * Creates a ground mesh.
  55514. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55515. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55516. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55518. */
  55519. MeshBuilder.CreateGround = function (name, options, scene) {
  55520. var ground = new BABYLON.GroundMesh(name, scene);
  55521. ground._setReady(false);
  55522. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55523. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55524. ground._width = options.width || 1;
  55525. ground._height = options.height || 1;
  55526. ground._maxX = ground._width / 2;
  55527. ground._maxZ = ground._height / 2;
  55528. ground._minX = -ground._maxX;
  55529. ground._minZ = -ground._maxZ;
  55530. var vertexData = BABYLON.VertexData.CreateGround(options);
  55531. vertexData.applyToMesh(ground, options.updatable);
  55532. ground._setReady(true);
  55533. return ground;
  55534. };
  55535. /**
  55536. * Creates a tiled ground mesh.
  55537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55538. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55539. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55540. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55541. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55542. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55543. * numbers of subdivisions on the ground width and height of each tile.
  55544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55545. */
  55546. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55547. var tiledGround = new BABYLON.Mesh(name, scene);
  55548. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55549. vertexData.applyToMesh(tiledGround, options.updatable);
  55550. return tiledGround;
  55551. };
  55552. /**
  55553. * Creates a ground mesh from a height map.
  55554. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55555. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55556. * The parameter `url` sets the URL of the height map image resource.
  55557. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55558. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55559. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55560. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55561. * 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.
  55562. * 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).
  55563. * This function is passed the newly built mesh :
  55564. * ```javascript
  55565. * function(mesh) { // do things
  55566. * return; }
  55567. * ```
  55568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55569. */
  55570. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55571. var width = options.width || 10.0;
  55572. var height = options.height || 10.0;
  55573. var subdivisions = options.subdivisions || 1 | 0;
  55574. var minHeight = options.minHeight || 0.0;
  55575. var maxHeight = options.maxHeight || 1.0;
  55576. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55577. var updatable = options.updatable;
  55578. var onReady = options.onReady;
  55579. var ground = new BABYLON.GroundMesh(name, scene);
  55580. ground._subdivisionsX = subdivisions;
  55581. ground._subdivisionsY = subdivisions;
  55582. ground._width = width;
  55583. ground._height = height;
  55584. ground._maxX = ground._width / 2.0;
  55585. ground._maxZ = ground._height / 2.0;
  55586. ground._minX = -ground._maxX;
  55587. ground._minZ = -ground._maxZ;
  55588. ground._setReady(false);
  55589. var onload = function (img) {
  55590. // Getting height map data
  55591. var canvas = document.createElement("canvas");
  55592. var context = canvas.getContext("2d");
  55593. if (!context) {
  55594. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55595. }
  55596. if (scene.isDisposed) {
  55597. return;
  55598. }
  55599. var bufferWidth = img.width;
  55600. var bufferHeight = img.height;
  55601. canvas.width = bufferWidth;
  55602. canvas.height = bufferHeight;
  55603. context.drawImage(img, 0, 0);
  55604. // Create VertexData from map data
  55605. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55606. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55607. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55608. width: width, height: height,
  55609. subdivisions: subdivisions,
  55610. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55611. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55612. });
  55613. vertexData.applyToMesh(ground, updatable);
  55614. ground._setReady(true);
  55615. //execute ready callback, if set
  55616. if (onReady) {
  55617. onReady(ground);
  55618. }
  55619. };
  55620. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55621. return ground;
  55622. };
  55623. /**
  55624. * Creates a polygon mesh.
  55625. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55626. * 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.
  55627. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55629. * 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).
  55630. * Remember you can only change the shape positions, not their number when updating a polygon.
  55631. */
  55632. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55633. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55634. var shape = options.shape;
  55635. var holes = options.holes || [];
  55636. var depth = options.depth || 0;
  55637. var contours = [];
  55638. var hole = [];
  55639. for (var i = 0; i < shape.length; i++) {
  55640. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55641. }
  55642. var epsilon = 0.00000001;
  55643. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55644. contours.pop();
  55645. }
  55646. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55647. for (var hNb = 0; hNb < holes.length; hNb++) {
  55648. hole = [];
  55649. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55650. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55651. }
  55652. polygonTriangulation.addHole(hole);
  55653. }
  55654. var polygon = polygonTriangulation.build(options.updatable, depth);
  55655. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55656. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55657. vertexData.applyToMesh(polygon, options.updatable);
  55658. return polygon;
  55659. };
  55660. ;
  55661. /**
  55662. * Creates an extruded polygon mesh, with depth in the Y direction.
  55663. * 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).
  55664. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55665. */
  55666. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55667. return MeshBuilder.CreatePolygon(name, options, scene);
  55668. };
  55669. ;
  55670. /**
  55671. * Creates a tube mesh.
  55672. * 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.
  55673. *
  55674. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55675. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55676. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55677. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55678. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55679. * 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.
  55680. * It must return a radius value (positive float) :
  55681. * ```javascript
  55682. * var radiusFunction = function(i, distance) {
  55683. * // do things
  55684. * return radius; }
  55685. * ```
  55686. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55687. * 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
  55688. * 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
  55689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55690. * 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).
  55691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55692. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55694. */
  55695. MeshBuilder.CreateTube = function (name, options, scene) {
  55696. var path = options.path;
  55697. var instance = options.instance;
  55698. var radius = 1.0;
  55699. if (instance) {
  55700. radius = instance.radius;
  55701. }
  55702. if (options.radius !== undefined) {
  55703. radius = options.radius;
  55704. }
  55705. ;
  55706. var tessellation = options.tessellation || 64 | 0;
  55707. var radiusFunction = options.radiusFunction || null;
  55708. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55709. var invertUV = options.invertUV || false;
  55710. var updatable = options.updatable;
  55711. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55712. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55713. // tube geometry
  55714. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55715. var tangents = path3D.getTangents();
  55716. var normals = path3D.getNormals();
  55717. var distances = path3D.getDistances();
  55718. var pi2 = Math.PI * 2;
  55719. var step = pi2 / tessellation * arc;
  55720. var returnRadius = function () { return radius; };
  55721. var radiusFunctionFinal = radiusFunction || returnRadius;
  55722. var circlePath;
  55723. var rad;
  55724. var normal;
  55725. var rotated;
  55726. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55727. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55728. for (var i = 0; i < path.length; i++) {
  55729. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55730. circlePath = Array(); // current circle array
  55731. normal = normals[i]; // current normal
  55732. for (var t = 0; t < tessellation; t++) {
  55733. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55734. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55735. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55736. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55737. circlePath[t] = rotated;
  55738. }
  55739. circlePaths[index] = circlePath;
  55740. index++;
  55741. }
  55742. // cap
  55743. var capPath = function (nbPoints, pathIndex) {
  55744. var pointCap = Array();
  55745. for (var i = 0; i < nbPoints; i++) {
  55746. pointCap.push(path[pathIndex]);
  55747. }
  55748. return pointCap;
  55749. };
  55750. switch (cap) {
  55751. case BABYLON.Mesh.NO_CAP:
  55752. break;
  55753. case BABYLON.Mesh.CAP_START:
  55754. circlePaths[0] = capPath(tessellation, 0);
  55755. circlePaths[1] = circlePaths[2].slice(0);
  55756. break;
  55757. case BABYLON.Mesh.CAP_END:
  55758. circlePaths[index] = circlePaths[index - 1].slice(0);
  55759. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55760. break;
  55761. case BABYLON.Mesh.CAP_ALL:
  55762. circlePaths[0] = capPath(tessellation, 0);
  55763. circlePaths[1] = circlePaths[2].slice(0);
  55764. circlePaths[index] = circlePaths[index - 1].slice(0);
  55765. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55766. break;
  55767. default:
  55768. break;
  55769. }
  55770. return circlePaths;
  55771. };
  55772. var path3D;
  55773. var pathArray;
  55774. if (instance) {
  55775. var arc = options.arc || instance.arc;
  55776. path3D = (instance.path3D).update(path);
  55777. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55778. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55779. instance.path3D = path3D;
  55780. instance.pathArray = pathArray;
  55781. instance.arc = arc;
  55782. instance.radius = radius;
  55783. return instance;
  55784. }
  55785. // tube creation
  55786. path3D = new BABYLON.Path3D(path);
  55787. var newPathArray = new Array();
  55788. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55789. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55790. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55791. tube.pathArray = pathArray;
  55792. tube.path3D = path3D;
  55793. tube.tessellation = tessellation;
  55794. tube.cap = cap;
  55795. tube.arc = options.arc;
  55796. tube.radius = radius;
  55797. return tube;
  55798. };
  55799. /**
  55800. * Creates a polyhedron mesh.
  55801. *
  55802. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55803. * 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
  55804. * to choose the wanted type.
  55805. * The parameter `size` (positive float, default 1) sets the polygon size.
  55806. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55807. * 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`.
  55808. * 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
  55809. * 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)`).
  55810. * 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
  55811. * 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.
  55812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55813. * 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).
  55814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55815. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55816. */
  55817. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55818. var polyhedron = new BABYLON.Mesh(name, scene);
  55819. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55820. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55821. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55822. vertexData.applyToMesh(polyhedron, options.updatable);
  55823. return polyhedron;
  55824. };
  55825. /**
  55826. * Creates a decal mesh.
  55827. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55828. * 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.
  55829. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55830. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55831. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55832. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55833. */
  55834. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55835. var indices = sourceMesh.getIndices();
  55836. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55837. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55838. var position = options.position || BABYLON.Vector3.Zero();
  55839. var normal = options.normal || BABYLON.Vector3.Up();
  55840. var size = options.size || BABYLON.Vector3.One();
  55841. var angle = options.angle || 0;
  55842. // Getting correct rotation
  55843. if (!normal) {
  55844. var target = new BABYLON.Vector3(0, 0, 1);
  55845. var camera = sourceMesh.getScene().activeCamera;
  55846. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55847. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55848. }
  55849. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55850. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55851. var pitch = Math.atan2(normal.y, len);
  55852. // Matrix
  55853. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55854. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55855. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55856. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55857. var vertexData = new BABYLON.VertexData();
  55858. vertexData.indices = [];
  55859. vertexData.positions = [];
  55860. vertexData.normals = [];
  55861. vertexData.uvs = [];
  55862. var currentVertexDataIndex = 0;
  55863. var extractDecalVector3 = function (indexId) {
  55864. var result = new BABYLON.PositionNormalVertex();
  55865. if (!indices || !positions || !normals) {
  55866. return result;
  55867. }
  55868. var vertexId = indices[indexId];
  55869. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55870. // Send vector to decal local world
  55871. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55872. // Get normal
  55873. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55874. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55875. return result;
  55876. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55877. var clip = function (vertices, axis) {
  55878. if (vertices.length === 0) {
  55879. return vertices;
  55880. }
  55881. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55882. var clipVertices = function (v0, v1) {
  55883. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55884. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55885. };
  55886. var result = new Array();
  55887. for (var index = 0; index < vertices.length; index += 3) {
  55888. var v1Out;
  55889. var v2Out;
  55890. var v3Out;
  55891. var total = 0;
  55892. var nV1 = null;
  55893. var nV2 = null;
  55894. var nV3 = null;
  55895. var nV4 = null;
  55896. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55897. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55898. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55899. v1Out = d1 > 0;
  55900. v2Out = d2 > 0;
  55901. v3Out = d3 > 0;
  55902. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55903. switch (total) {
  55904. case 0:
  55905. result.push(vertices[index]);
  55906. result.push(vertices[index + 1]);
  55907. result.push(vertices[index + 2]);
  55908. break;
  55909. case 1:
  55910. if (v1Out) {
  55911. nV1 = vertices[index + 1];
  55912. nV2 = vertices[index + 2];
  55913. nV3 = clipVertices(vertices[index], nV1);
  55914. nV4 = clipVertices(vertices[index], nV2);
  55915. }
  55916. if (v2Out) {
  55917. nV1 = vertices[index];
  55918. nV2 = vertices[index + 2];
  55919. nV3 = clipVertices(vertices[index + 1], nV1);
  55920. nV4 = clipVertices(vertices[index + 1], nV2);
  55921. result.push(nV3);
  55922. result.push(nV2.clone());
  55923. result.push(nV1.clone());
  55924. result.push(nV2.clone());
  55925. result.push(nV3.clone());
  55926. result.push(nV4);
  55927. break;
  55928. }
  55929. if (v3Out) {
  55930. nV1 = vertices[index];
  55931. nV2 = vertices[index + 1];
  55932. nV3 = clipVertices(vertices[index + 2], nV1);
  55933. nV4 = clipVertices(vertices[index + 2], nV2);
  55934. }
  55935. if (nV1 && nV2 && nV3 && nV4) {
  55936. result.push(nV1.clone());
  55937. result.push(nV2.clone());
  55938. result.push(nV3);
  55939. result.push(nV4);
  55940. result.push(nV3.clone());
  55941. result.push(nV2.clone());
  55942. }
  55943. break;
  55944. case 2:
  55945. if (!v1Out) {
  55946. nV1 = vertices[index].clone();
  55947. nV2 = clipVertices(nV1, vertices[index + 1]);
  55948. nV3 = clipVertices(nV1, vertices[index + 2]);
  55949. result.push(nV1);
  55950. result.push(nV2);
  55951. result.push(nV3);
  55952. }
  55953. if (!v2Out) {
  55954. nV1 = vertices[index + 1].clone();
  55955. nV2 = clipVertices(nV1, vertices[index + 2]);
  55956. nV3 = clipVertices(nV1, vertices[index]);
  55957. result.push(nV1);
  55958. result.push(nV2);
  55959. result.push(nV3);
  55960. }
  55961. if (!v3Out) {
  55962. nV1 = vertices[index + 2].clone();
  55963. nV2 = clipVertices(nV1, vertices[index]);
  55964. nV3 = clipVertices(nV1, vertices[index + 1]);
  55965. result.push(nV1);
  55966. result.push(nV2);
  55967. result.push(nV3);
  55968. }
  55969. break;
  55970. case 3:
  55971. break;
  55972. }
  55973. }
  55974. return result;
  55975. };
  55976. for (var index = 0; index < indices.length; index += 3) {
  55977. var faceVertices = new Array();
  55978. faceVertices.push(extractDecalVector3(index));
  55979. faceVertices.push(extractDecalVector3(index + 1));
  55980. faceVertices.push(extractDecalVector3(index + 2));
  55981. // Clip
  55982. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55983. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55984. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55985. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55986. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55987. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55988. if (faceVertices.length === 0) {
  55989. continue;
  55990. }
  55991. // Add UVs and get back to world
  55992. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55993. var vertex = faceVertices[vIndex];
  55994. //TODO check for Int32Array | Uint32Array | Uint16Array
  55995. vertexData.indices.push(currentVertexDataIndex);
  55996. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55997. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55998. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55999. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56000. currentVertexDataIndex++;
  56001. }
  56002. }
  56003. // Return mesh
  56004. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56005. vertexData.applyToMesh(decal);
  56006. decal.position = position.clone();
  56007. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56008. return decal;
  56009. };
  56010. // Privates
  56011. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56012. // extrusion geometry
  56013. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56014. var tangents = path3D.getTangents();
  56015. var normals = path3D.getNormals();
  56016. var binormals = path3D.getBinormals();
  56017. var distances = path3D.getDistances();
  56018. var angle = 0;
  56019. var returnScale = function () { return scale !== null ? scale : 1; };
  56020. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56021. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56022. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56023. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56024. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56025. for (var i = 0; i < curve.length; i++) {
  56026. var shapePath = new Array();
  56027. var angleStep = rotate(i, distances[i]);
  56028. var scaleRatio = scl(i, distances[i]);
  56029. for (var p = 0; p < shape.length; p++) {
  56030. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56031. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56032. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56033. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56034. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56035. shapePath[p] = rotated;
  56036. }
  56037. shapePaths[index] = shapePath;
  56038. angle += angleStep;
  56039. index++;
  56040. }
  56041. // cap
  56042. var capPath = function (shapePath) {
  56043. var pointCap = Array();
  56044. var barycenter = BABYLON.Vector3.Zero();
  56045. var i;
  56046. for (i = 0; i < shapePath.length; i++) {
  56047. barycenter.addInPlace(shapePath[i]);
  56048. }
  56049. barycenter.scaleInPlace(1.0 / shapePath.length);
  56050. for (i = 0; i < shapePath.length; i++) {
  56051. pointCap.push(barycenter);
  56052. }
  56053. return pointCap;
  56054. };
  56055. switch (cap) {
  56056. case BABYLON.Mesh.NO_CAP:
  56057. break;
  56058. case BABYLON.Mesh.CAP_START:
  56059. shapePaths[0] = capPath(shapePaths[2]);
  56060. shapePaths[1] = shapePaths[2];
  56061. break;
  56062. case BABYLON.Mesh.CAP_END:
  56063. shapePaths[index] = shapePaths[index - 1];
  56064. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56065. break;
  56066. case BABYLON.Mesh.CAP_ALL:
  56067. shapePaths[0] = capPath(shapePaths[2]);
  56068. shapePaths[1] = shapePaths[2];
  56069. shapePaths[index] = shapePaths[index - 1];
  56070. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56071. break;
  56072. default:
  56073. break;
  56074. }
  56075. return shapePaths;
  56076. };
  56077. var path3D;
  56078. var pathArray;
  56079. if (instance) {
  56080. path3D = (instance.path3D).update(curve);
  56081. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56082. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56083. return instance;
  56084. }
  56085. // extruded shape creation
  56086. path3D = new BABYLON.Path3D(curve);
  56087. var newShapePaths = new Array();
  56088. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56089. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56090. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56091. extrudedGeneric.pathArray = pathArray;
  56092. extrudedGeneric.path3D = path3D;
  56093. extrudedGeneric.cap = cap;
  56094. return extrudedGeneric;
  56095. };
  56096. return MeshBuilder;
  56097. }());
  56098. BABYLON.MeshBuilder = MeshBuilder;
  56099. })(BABYLON || (BABYLON = {}));
  56100. //# sourceMappingURL=babylon.meshBuilder.js.map
  56101. var BABYLON;
  56102. (function (BABYLON) {
  56103. /**
  56104. * Draco compression (https://google.github.io/draco/)
  56105. */
  56106. var DracoCompression = /** @class */ (function () {
  56107. /**
  56108. * Constructor
  56109. * @param numWorkers The number of workers for async operations
  56110. */
  56111. function DracoCompression(numWorkers) {
  56112. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56113. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56114. if (!workerBlobUrl || !Worker) {
  56115. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56116. return;
  56117. }
  56118. var workers = new Array(numWorkers);
  56119. for (var i = 0; i < workers.length; i++) {
  56120. var worker = new Worker(workerBlobUrl);
  56121. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56122. workers[i] = worker;
  56123. }
  56124. this._workerPool = new BABYLON.WorkerPool(workers);
  56125. }
  56126. /**
  56127. * Stop all async operations and release resources.
  56128. */
  56129. DracoCompression.prototype.dispose = function () {
  56130. this._workerPool.dispose();
  56131. delete this._workerPool;
  56132. };
  56133. /**
  56134. * Decode Draco compressed mesh data to vertex data.
  56135. * @param data The array buffer view for the Draco compression data
  56136. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56137. * @returns A promise that resolves with the decoded vertex data
  56138. */
  56139. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56140. var _this = this;
  56141. return new Promise(function (resolve, reject) {
  56142. _this._workerPool.push(function (worker, onComplete) {
  56143. var vertexData = new BABYLON.VertexData();
  56144. var onError = function (error) {
  56145. worker.removeEventListener("error", onError);
  56146. worker.removeEventListener("message", onMessage);
  56147. reject(error);
  56148. onComplete();
  56149. };
  56150. var onMessage = function (message) {
  56151. if (message.data === "done") {
  56152. worker.removeEventListener("error", onError);
  56153. worker.removeEventListener("message", onMessage);
  56154. resolve(vertexData);
  56155. onComplete();
  56156. }
  56157. else if (message.data.id === "indices") {
  56158. vertexData.indices = message.data.value;
  56159. }
  56160. else {
  56161. vertexData.set(message.data.value, message.data.id);
  56162. }
  56163. };
  56164. worker.addEventListener("error", onError);
  56165. worker.addEventListener("message", onMessage);
  56166. var dataCopy = new Uint8Array(data.byteLength);
  56167. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56168. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56169. });
  56170. });
  56171. };
  56172. /**
  56173. * The worker function that gets converted to a blob url to pass into a worker.
  56174. */
  56175. DracoCompression._Worker = function () {
  56176. // self is actually a DedicatedWorkerGlobalScope
  56177. var _self = self;
  56178. var decodeMesh = function (data, attributes) {
  56179. var dracoModule = new DracoDecoderModule();
  56180. var buffer = new dracoModule.DecoderBuffer();
  56181. buffer.Init(data, data.byteLength);
  56182. var decoder = new dracoModule.Decoder();
  56183. var geometry;
  56184. var status;
  56185. try {
  56186. var type = decoder.GetEncodedGeometryType(buffer);
  56187. switch (type) {
  56188. case dracoModule.TRIANGULAR_MESH:
  56189. geometry = new dracoModule.Mesh();
  56190. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56191. break;
  56192. case dracoModule.POINT_CLOUD:
  56193. geometry = new dracoModule.PointCloud();
  56194. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56195. break;
  56196. default:
  56197. throw new Error("Invalid geometry type " + type);
  56198. }
  56199. if (!status.ok() || !geometry.ptr) {
  56200. throw new Error(status.error_msg());
  56201. }
  56202. var numPoints = geometry.num_points();
  56203. if (type === dracoModule.TRIANGULAR_MESH) {
  56204. var numFaces = geometry.num_faces();
  56205. var faceIndices = new dracoModule.DracoInt32Array();
  56206. try {
  56207. var indices = new Uint32Array(numFaces * 3);
  56208. for (var i = 0; i < numFaces; i++) {
  56209. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56210. var offset = i * 3;
  56211. indices[offset + 0] = faceIndices.GetValue(0);
  56212. indices[offset + 1] = faceIndices.GetValue(1);
  56213. indices[offset + 2] = faceIndices.GetValue(2);
  56214. }
  56215. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56216. }
  56217. finally {
  56218. dracoModule.destroy(faceIndices);
  56219. }
  56220. }
  56221. for (var kind in attributes) {
  56222. var uniqueId = attributes[kind];
  56223. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56224. var dracoData = new dracoModule.DracoFloat32Array();
  56225. try {
  56226. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56227. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56228. for (var i = 0; i < babylonData.length; i++) {
  56229. babylonData[i] = dracoData.GetValue(i);
  56230. }
  56231. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56232. }
  56233. finally {
  56234. dracoModule.destroy(dracoData);
  56235. }
  56236. }
  56237. }
  56238. finally {
  56239. if (geometry) {
  56240. dracoModule.destroy(geometry);
  56241. }
  56242. dracoModule.destroy(decoder);
  56243. dracoModule.destroy(buffer);
  56244. }
  56245. _self.postMessage("done");
  56246. };
  56247. _self.onmessage = function (event) {
  56248. switch (event.data.id) {
  56249. case "initDecoder": {
  56250. importScripts(event.data.url);
  56251. break;
  56252. }
  56253. case "decodeMesh": {
  56254. decodeMesh(event.data.data, event.data.attributes);
  56255. break;
  56256. }
  56257. }
  56258. };
  56259. };
  56260. DracoCompression._GetDefaultDecoderUrl = function () {
  56261. if (!BABYLON.Tools.IsWindowObjectExist) {
  56262. return null;
  56263. }
  56264. for (var i = 0; i < document.scripts.length; i++) {
  56265. if (document.scripts[i].type === "text/x-draco-decoder") {
  56266. return document.scripts[i].src;
  56267. }
  56268. }
  56269. return null;
  56270. };
  56271. /**
  56272. * Gets the url to the draco decoder if available.
  56273. */
  56274. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56275. return DracoCompression;
  56276. }());
  56277. BABYLON.DracoCompression = DracoCompression;
  56278. })(BABYLON || (BABYLON = {}));
  56279. //# sourceMappingURL=babylon.dracoCompression.js.map
  56280. var BABYLON;
  56281. (function (BABYLON) {
  56282. var AudioEngine = /** @class */ (function () {
  56283. function AudioEngine() {
  56284. this._audioContext = null;
  56285. this._audioContextInitialized = false;
  56286. this.canUseWebAudio = false;
  56287. this.WarnedWebAudioUnsupported = false;
  56288. this.unlocked = false;
  56289. this.isMP3supported = false;
  56290. this.isOGGsupported = false;
  56291. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56292. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56293. this.canUseWebAudio = true;
  56294. }
  56295. var audioElem = document.createElement('audio');
  56296. try {
  56297. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56298. this.isMP3supported = true;
  56299. }
  56300. }
  56301. catch (e) {
  56302. // protect error during capability check.
  56303. }
  56304. try {
  56305. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56306. this.isOGGsupported = true;
  56307. }
  56308. }
  56309. catch (e) {
  56310. // protect error during capability check.
  56311. }
  56312. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56313. this._unlockiOSaudio();
  56314. }
  56315. else {
  56316. this.unlocked = true;
  56317. }
  56318. }
  56319. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56320. get: function () {
  56321. if (!this._audioContextInitialized) {
  56322. this._initializeAudioContext();
  56323. }
  56324. return this._audioContext;
  56325. },
  56326. enumerable: true,
  56327. configurable: true
  56328. });
  56329. AudioEngine.prototype._unlockiOSaudio = function () {
  56330. var _this = this;
  56331. var unlockaudio = function () {
  56332. if (!_this.audioContext) {
  56333. return;
  56334. }
  56335. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56336. var source = _this.audioContext.createBufferSource();
  56337. source.buffer = buffer;
  56338. source.connect(_this.audioContext.destination);
  56339. source.start(0);
  56340. setTimeout(function () {
  56341. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56342. _this.unlocked = true;
  56343. window.removeEventListener('touchend', unlockaudio, false);
  56344. if (_this.onAudioUnlocked) {
  56345. _this.onAudioUnlocked();
  56346. }
  56347. }
  56348. }, 0);
  56349. };
  56350. window.addEventListener('touchend', unlockaudio, false);
  56351. };
  56352. AudioEngine.prototype._initializeAudioContext = function () {
  56353. try {
  56354. if (this.canUseWebAudio) {
  56355. this._audioContext = new AudioContext();
  56356. // create a global volume gain node
  56357. this.masterGain = this._audioContext.createGain();
  56358. this.masterGain.gain.value = 1;
  56359. this.masterGain.connect(this._audioContext.destination);
  56360. this._audioContextInitialized = true;
  56361. }
  56362. }
  56363. catch (e) {
  56364. this.canUseWebAudio = false;
  56365. BABYLON.Tools.Error("Web Audio: " + e.message);
  56366. }
  56367. };
  56368. AudioEngine.prototype.dispose = function () {
  56369. if (this.canUseWebAudio && this._audioContextInitialized) {
  56370. if (this._connectedAnalyser && this._audioContext) {
  56371. this._connectedAnalyser.stopDebugCanvas();
  56372. this._connectedAnalyser.dispose();
  56373. this.masterGain.disconnect();
  56374. this.masterGain.connect(this._audioContext.destination);
  56375. this._connectedAnalyser = null;
  56376. }
  56377. this.masterGain.gain.value = 1;
  56378. }
  56379. this.WarnedWebAudioUnsupported = false;
  56380. };
  56381. AudioEngine.prototype.getGlobalVolume = function () {
  56382. if (this.canUseWebAudio && this._audioContextInitialized) {
  56383. return this.masterGain.gain.value;
  56384. }
  56385. else {
  56386. return -1;
  56387. }
  56388. };
  56389. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56390. if (this.canUseWebAudio && this._audioContextInitialized) {
  56391. this.masterGain.gain.value = newVolume;
  56392. }
  56393. };
  56394. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56395. if (this._connectedAnalyser) {
  56396. this._connectedAnalyser.stopDebugCanvas();
  56397. }
  56398. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56399. this._connectedAnalyser = analyser;
  56400. this.masterGain.disconnect();
  56401. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56402. }
  56403. };
  56404. return AudioEngine;
  56405. }());
  56406. BABYLON.AudioEngine = AudioEngine;
  56407. })(BABYLON || (BABYLON = {}));
  56408. //# sourceMappingURL=babylon.audioEngine.js.map
  56409. var BABYLON;
  56410. (function (BABYLON) {
  56411. var Sound = /** @class */ (function () {
  56412. /**
  56413. * Create a sound and attach it to a scene
  56414. * @param name Name of your sound
  56415. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56416. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56417. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56418. */
  56419. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56420. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56421. var _this = this;
  56422. this.autoplay = false;
  56423. this.loop = false;
  56424. this.useCustomAttenuation = false;
  56425. this.spatialSound = false;
  56426. this.refDistance = 1;
  56427. this.rolloffFactor = 1;
  56428. this.maxDistance = 100;
  56429. this.distanceModel = "linear";
  56430. this._panningModel = "equalpower";
  56431. this._playbackRate = 1;
  56432. this._streaming = false;
  56433. this._startTime = 0;
  56434. this._startOffset = 0;
  56435. this._position = BABYLON.Vector3.Zero();
  56436. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56437. this._volume = 1;
  56438. this._isReadyToPlay = false;
  56439. this.isPlaying = false;
  56440. this.isPaused = false;
  56441. this._isDirectional = false;
  56442. // Used if you'd like to create a directional sound.
  56443. // If not set, the sound will be omnidirectional
  56444. this._coneInnerAngle = 360;
  56445. this._coneOuterAngle = 360;
  56446. this._coneOuterGain = 0;
  56447. this._isOutputConnected = false;
  56448. this._urlType = "Unknown";
  56449. this.name = name;
  56450. this._scene = scene;
  56451. this._readyToPlayCallback = readyToPlayCallback;
  56452. // Default custom attenuation function is a linear attenuation
  56453. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56454. if (currentDistance < maxDistance) {
  56455. return currentVolume * (1 - currentDistance / maxDistance);
  56456. }
  56457. else {
  56458. return 0;
  56459. }
  56460. };
  56461. if (options) {
  56462. this.autoplay = options.autoplay || false;
  56463. this.loop = options.loop || false;
  56464. // if volume === 0, we need another way to check this option
  56465. if (options.volume !== undefined) {
  56466. this._volume = options.volume;
  56467. }
  56468. this.spatialSound = options.spatialSound || false;
  56469. this.maxDistance = options.maxDistance || 100;
  56470. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56471. this.rolloffFactor = options.rolloffFactor || 1;
  56472. this.refDistance = options.refDistance || 1;
  56473. this.distanceModel = options.distanceModel || "linear";
  56474. this._playbackRate = options.playbackRate || 1;
  56475. this._streaming = options.streaming || false;
  56476. }
  56477. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56478. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56479. this._soundGain.gain.value = this._volume;
  56480. this._inputAudioNode = this._soundGain;
  56481. this._ouputAudioNode = this._soundGain;
  56482. if (this.spatialSound) {
  56483. this._createSpatialParameters();
  56484. }
  56485. this._scene.mainSoundTrack.AddSound(this);
  56486. var validParameter = true;
  56487. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56488. if (urlOrArrayBuffer) {
  56489. if (typeof (urlOrArrayBuffer) === "string")
  56490. this._urlType = "String";
  56491. if (Array.isArray(urlOrArrayBuffer))
  56492. this._urlType = "Array";
  56493. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56494. this._urlType = "ArrayBuffer";
  56495. var urls = [];
  56496. var codecSupportedFound = false;
  56497. switch (this._urlType) {
  56498. case "ArrayBuffer":
  56499. if (urlOrArrayBuffer.byteLength > 0) {
  56500. codecSupportedFound = true;
  56501. this._soundLoaded(urlOrArrayBuffer);
  56502. }
  56503. break;
  56504. case "String":
  56505. urls.push(urlOrArrayBuffer);
  56506. case "Array":
  56507. if (urls.length === 0)
  56508. urls = urlOrArrayBuffer;
  56509. // If we found a supported format, we load it immediately and stop the loop
  56510. for (var i = 0; i < urls.length; i++) {
  56511. var url = urls[i];
  56512. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56513. codecSupportedFound = true;
  56514. }
  56515. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56516. codecSupportedFound = true;
  56517. }
  56518. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56519. codecSupportedFound = true;
  56520. }
  56521. if (url.indexOf("blob:") !== -1) {
  56522. codecSupportedFound = true;
  56523. }
  56524. if (codecSupportedFound) {
  56525. // Loading sound using XHR2
  56526. if (!this._streaming) {
  56527. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56528. }
  56529. else {
  56530. this._htmlAudioElement = new Audio(url);
  56531. this._htmlAudioElement.controls = false;
  56532. this._htmlAudioElement.loop = this.loop;
  56533. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56534. this._htmlAudioElement.preload = "auto";
  56535. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56536. _this._isReadyToPlay = true;
  56537. if (_this.autoplay) {
  56538. _this.play();
  56539. }
  56540. if (_this._readyToPlayCallback) {
  56541. _this._readyToPlayCallback();
  56542. }
  56543. });
  56544. document.body.appendChild(this._htmlAudioElement);
  56545. }
  56546. break;
  56547. }
  56548. }
  56549. break;
  56550. default:
  56551. validParameter = false;
  56552. break;
  56553. }
  56554. if (!validParameter) {
  56555. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56556. }
  56557. else {
  56558. if (!codecSupportedFound) {
  56559. this._isReadyToPlay = true;
  56560. // Simulating a ready to play event to avoid breaking code path
  56561. if (this._readyToPlayCallback) {
  56562. window.setTimeout(function () {
  56563. if (_this._readyToPlayCallback) {
  56564. _this._readyToPlayCallback();
  56565. }
  56566. }, 1000);
  56567. }
  56568. }
  56569. }
  56570. }
  56571. }
  56572. else {
  56573. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56574. this._scene.mainSoundTrack.AddSound(this);
  56575. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56576. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56577. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56578. }
  56579. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56580. if (this._readyToPlayCallback) {
  56581. window.setTimeout(function () {
  56582. if (_this._readyToPlayCallback) {
  56583. _this._readyToPlayCallback();
  56584. }
  56585. }, 1000);
  56586. }
  56587. }
  56588. }
  56589. Sound.prototype.dispose = function () {
  56590. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56591. if (this.isPlaying) {
  56592. this.stop();
  56593. }
  56594. this._isReadyToPlay = false;
  56595. if (this.soundTrackId === -1) {
  56596. this._scene.mainSoundTrack.RemoveSound(this);
  56597. }
  56598. else {
  56599. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56600. }
  56601. if (this._soundGain) {
  56602. this._soundGain.disconnect();
  56603. this._soundGain = null;
  56604. }
  56605. if (this._soundPanner) {
  56606. this._soundPanner.disconnect();
  56607. this._soundPanner = null;
  56608. }
  56609. if (this._soundSource) {
  56610. this._soundSource.disconnect();
  56611. this._soundSource = null;
  56612. }
  56613. this._audioBuffer = null;
  56614. if (this._htmlAudioElement) {
  56615. this._htmlAudioElement.pause();
  56616. this._htmlAudioElement.src = "";
  56617. document.body.removeChild(this._htmlAudioElement);
  56618. }
  56619. if (this._connectedMesh && this._registerFunc) {
  56620. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56621. this._connectedMesh = null;
  56622. }
  56623. }
  56624. };
  56625. Sound.prototype.isReady = function () {
  56626. return this._isReadyToPlay;
  56627. };
  56628. Sound.prototype._soundLoaded = function (audioData) {
  56629. var _this = this;
  56630. if (!BABYLON.Engine.audioEngine.audioContext) {
  56631. return;
  56632. }
  56633. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56634. _this._audioBuffer = buffer;
  56635. _this._isReadyToPlay = true;
  56636. if (_this.autoplay) {
  56637. _this.play();
  56638. }
  56639. if (_this._readyToPlayCallback) {
  56640. _this._readyToPlayCallback();
  56641. }
  56642. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56643. };
  56644. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56645. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56646. this._audioBuffer = audioBuffer;
  56647. this._isReadyToPlay = true;
  56648. }
  56649. };
  56650. Sound.prototype.updateOptions = function (options) {
  56651. if (options) {
  56652. this.loop = options.loop || this.loop;
  56653. this.maxDistance = options.maxDistance || this.maxDistance;
  56654. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56655. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56656. this.refDistance = options.refDistance || this.refDistance;
  56657. this.distanceModel = options.distanceModel || this.distanceModel;
  56658. this._playbackRate = options.playbackRate || this._playbackRate;
  56659. this._updateSpatialParameters();
  56660. if (this.isPlaying) {
  56661. if (this._streaming) {
  56662. this._htmlAudioElement.playbackRate = this._playbackRate;
  56663. }
  56664. else {
  56665. if (this._soundSource) {
  56666. this._soundSource.playbackRate.value = this._playbackRate;
  56667. }
  56668. }
  56669. }
  56670. }
  56671. };
  56672. Sound.prototype._createSpatialParameters = function () {
  56673. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56674. if (this._scene.headphone) {
  56675. this._panningModel = "HRTF";
  56676. }
  56677. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56678. this._updateSpatialParameters();
  56679. this._soundPanner.connect(this._ouputAudioNode);
  56680. this._inputAudioNode = this._soundPanner;
  56681. }
  56682. };
  56683. Sound.prototype._updateSpatialParameters = function () {
  56684. if (this.spatialSound && this._soundPanner) {
  56685. if (this.useCustomAttenuation) {
  56686. // Tricks to disable in a way embedded Web Audio attenuation
  56687. this._soundPanner.distanceModel = "linear";
  56688. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56689. this._soundPanner.refDistance = 1;
  56690. this._soundPanner.rolloffFactor = 1;
  56691. this._soundPanner.panningModel = this._panningModel;
  56692. }
  56693. else {
  56694. this._soundPanner.distanceModel = this.distanceModel;
  56695. this._soundPanner.maxDistance = this.maxDistance;
  56696. this._soundPanner.refDistance = this.refDistance;
  56697. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56698. this._soundPanner.panningModel = this._panningModel;
  56699. }
  56700. }
  56701. };
  56702. Sound.prototype.switchPanningModelToHRTF = function () {
  56703. this._panningModel = "HRTF";
  56704. this._switchPanningModel();
  56705. };
  56706. Sound.prototype.switchPanningModelToEqualPower = function () {
  56707. this._panningModel = "equalpower";
  56708. this._switchPanningModel();
  56709. };
  56710. Sound.prototype._switchPanningModel = function () {
  56711. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56712. this._soundPanner.panningModel = this._panningModel;
  56713. }
  56714. };
  56715. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56716. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56717. if (this._isOutputConnected) {
  56718. this._ouputAudioNode.disconnect();
  56719. }
  56720. this._ouputAudioNode.connect(soundTrackAudioNode);
  56721. this._isOutputConnected = true;
  56722. }
  56723. };
  56724. /**
  56725. * Transform this sound into a directional source
  56726. * @param coneInnerAngle Size of the inner cone in degree
  56727. * @param coneOuterAngle Size of the outer cone in degree
  56728. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56729. */
  56730. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56731. if (coneOuterAngle < coneInnerAngle) {
  56732. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56733. return;
  56734. }
  56735. this._coneInnerAngle = coneInnerAngle;
  56736. this._coneOuterAngle = coneOuterAngle;
  56737. this._coneOuterGain = coneOuterGain;
  56738. this._isDirectional = true;
  56739. if (this.isPlaying && this.loop) {
  56740. this.stop();
  56741. this.play();
  56742. }
  56743. };
  56744. Sound.prototype.setPosition = function (newPosition) {
  56745. this._position = newPosition;
  56746. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56747. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56748. }
  56749. };
  56750. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56751. this._localDirection = newLocalDirection;
  56752. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56753. this._updateDirection();
  56754. }
  56755. };
  56756. Sound.prototype._updateDirection = function () {
  56757. if (!this._connectedMesh || !this._soundPanner) {
  56758. return;
  56759. }
  56760. var mat = this._connectedMesh.getWorldMatrix();
  56761. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56762. direction.normalize();
  56763. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56764. };
  56765. Sound.prototype.updateDistanceFromListener = function () {
  56766. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56767. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56768. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56769. }
  56770. };
  56771. Sound.prototype.setAttenuationFunction = function (callback) {
  56772. this._customAttenuationFunction = callback;
  56773. };
  56774. /**
  56775. * Play the sound
  56776. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56777. * @param offset (optional) Start the sound setting it at a specific time
  56778. */
  56779. Sound.prototype.play = function (time, offset) {
  56780. var _this = this;
  56781. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56782. try {
  56783. if (this._startOffset < 0) {
  56784. time = -this._startOffset;
  56785. this._startOffset = 0;
  56786. }
  56787. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56788. if (!this._soundSource || !this._streamingSource) {
  56789. if (this.spatialSound && this._soundPanner) {
  56790. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56791. if (this._isDirectional) {
  56792. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56793. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56794. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56795. if (this._connectedMesh) {
  56796. this._updateDirection();
  56797. }
  56798. else {
  56799. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56800. }
  56801. }
  56802. }
  56803. }
  56804. if (this._streaming) {
  56805. if (!this._streamingSource) {
  56806. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56807. this._htmlAudioElement.onended = function () { _this._onended(); };
  56808. this._htmlAudioElement.playbackRate = this._playbackRate;
  56809. }
  56810. this._streamingSource.disconnect();
  56811. this._streamingSource.connect(this._inputAudioNode);
  56812. this._htmlAudioElement.play();
  56813. }
  56814. else {
  56815. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56816. this._soundSource.buffer = this._audioBuffer;
  56817. this._soundSource.connect(this._inputAudioNode);
  56818. this._soundSource.loop = this.loop;
  56819. this._soundSource.playbackRate.value = this._playbackRate;
  56820. this._soundSource.onended = function () { _this._onended(); };
  56821. if (this._soundSource.buffer) {
  56822. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56823. }
  56824. }
  56825. this._startTime = startTime;
  56826. this.isPlaying = true;
  56827. this.isPaused = false;
  56828. }
  56829. catch (ex) {
  56830. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56831. }
  56832. }
  56833. };
  56834. Sound.prototype._onended = function () {
  56835. this.isPlaying = false;
  56836. if (this.onended) {
  56837. this.onended();
  56838. }
  56839. };
  56840. /**
  56841. * Stop the sound
  56842. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56843. */
  56844. Sound.prototype.stop = function (time) {
  56845. if (this.isPlaying) {
  56846. if (this._streaming) {
  56847. this._htmlAudioElement.pause();
  56848. // Test needed for Firefox or it will generate an Invalid State Error
  56849. if (this._htmlAudioElement.currentTime > 0) {
  56850. this._htmlAudioElement.currentTime = 0;
  56851. }
  56852. }
  56853. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56854. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56855. this._soundSource.stop(stopTime);
  56856. this._soundSource.onended = function () { };
  56857. if (!this.isPaused) {
  56858. this._startOffset = 0;
  56859. }
  56860. }
  56861. this.isPlaying = false;
  56862. }
  56863. };
  56864. Sound.prototype.pause = function () {
  56865. if (this.isPlaying) {
  56866. this.isPaused = true;
  56867. if (this._streaming) {
  56868. this._htmlAudioElement.pause();
  56869. }
  56870. else if (BABYLON.Engine.audioEngine.audioContext) {
  56871. this.stop(0);
  56872. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56873. }
  56874. }
  56875. };
  56876. Sound.prototype.setVolume = function (newVolume, time) {
  56877. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56878. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56879. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56880. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56881. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56882. }
  56883. else {
  56884. this._soundGain.gain.value = newVolume;
  56885. }
  56886. }
  56887. this._volume = newVolume;
  56888. };
  56889. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56890. this._playbackRate = newPlaybackRate;
  56891. if (this.isPlaying) {
  56892. if (this._streaming) {
  56893. this._htmlAudioElement.playbackRate = this._playbackRate;
  56894. }
  56895. else if (this._soundSource) {
  56896. this._soundSource.playbackRate.value = this._playbackRate;
  56897. }
  56898. }
  56899. };
  56900. Sound.prototype.getVolume = function () {
  56901. return this._volume;
  56902. };
  56903. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56904. var _this = this;
  56905. if (this._connectedMesh && this._registerFunc) {
  56906. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56907. this._registerFunc = null;
  56908. }
  56909. this._connectedMesh = meshToConnectTo;
  56910. if (!this.spatialSound) {
  56911. this.spatialSound = true;
  56912. this._createSpatialParameters();
  56913. if (this.isPlaying && this.loop) {
  56914. this.stop();
  56915. this.play();
  56916. }
  56917. }
  56918. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56919. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56920. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56921. };
  56922. Sound.prototype.detachFromMesh = function () {
  56923. if (this._connectedMesh && this._registerFunc) {
  56924. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56925. this._registerFunc = null;
  56926. this._connectedMesh = null;
  56927. }
  56928. };
  56929. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56930. if (!node.getBoundingInfo) {
  56931. return;
  56932. }
  56933. var mesh = node;
  56934. var boundingInfo = mesh.getBoundingInfo();
  56935. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56936. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56937. this._updateDirection();
  56938. }
  56939. };
  56940. Sound.prototype.clone = function () {
  56941. var _this = this;
  56942. if (!this._streaming) {
  56943. var setBufferAndRun = function () {
  56944. if (_this._isReadyToPlay) {
  56945. clonedSound._audioBuffer = _this.getAudioBuffer();
  56946. clonedSound._isReadyToPlay = true;
  56947. if (clonedSound.autoplay) {
  56948. clonedSound.play();
  56949. }
  56950. }
  56951. else {
  56952. window.setTimeout(setBufferAndRun, 300);
  56953. }
  56954. };
  56955. var currentOptions = {
  56956. autoplay: this.autoplay, loop: this.loop,
  56957. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56958. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56959. refDistance: this.refDistance, distanceModel: this.distanceModel
  56960. };
  56961. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56962. if (this.useCustomAttenuation) {
  56963. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56964. }
  56965. clonedSound.setPosition(this._position);
  56966. clonedSound.setPlaybackRate(this._playbackRate);
  56967. setBufferAndRun();
  56968. return clonedSound;
  56969. }
  56970. else {
  56971. return null;
  56972. }
  56973. };
  56974. Sound.prototype.getAudioBuffer = function () {
  56975. return this._audioBuffer;
  56976. };
  56977. Sound.prototype.serialize = function () {
  56978. var serializationObject = {
  56979. name: this.name,
  56980. url: this.name,
  56981. autoplay: this.autoplay,
  56982. loop: this.loop,
  56983. volume: this._volume,
  56984. spatialSound: this.spatialSound,
  56985. maxDistance: this.maxDistance,
  56986. rolloffFactor: this.rolloffFactor,
  56987. refDistance: this.refDistance,
  56988. distanceModel: this.distanceModel,
  56989. playbackRate: this._playbackRate,
  56990. panningModel: this._panningModel,
  56991. soundTrackId: this.soundTrackId
  56992. };
  56993. if (this.spatialSound) {
  56994. if (this._connectedMesh)
  56995. serializationObject.connectedMeshId = this._connectedMesh.id;
  56996. serializationObject.position = this._position.asArray();
  56997. serializationObject.refDistance = this.refDistance;
  56998. serializationObject.distanceModel = this.distanceModel;
  56999. serializationObject.isDirectional = this._isDirectional;
  57000. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57001. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57002. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57003. serializationObject.coneOuterGain = this._coneOuterGain;
  57004. }
  57005. return serializationObject;
  57006. };
  57007. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57008. var soundName = parsedSound.name;
  57009. var soundUrl;
  57010. if (parsedSound.url) {
  57011. soundUrl = rootUrl + parsedSound.url;
  57012. }
  57013. else {
  57014. soundUrl = rootUrl + soundName;
  57015. }
  57016. var options = {
  57017. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57018. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57019. rolloffFactor: parsedSound.rolloffFactor,
  57020. refDistance: parsedSound.refDistance,
  57021. distanceModel: parsedSound.distanceModel,
  57022. playbackRate: parsedSound.playbackRate
  57023. };
  57024. var newSound;
  57025. if (!sourceSound) {
  57026. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57027. scene._addPendingData(newSound);
  57028. }
  57029. else {
  57030. var setBufferAndRun = function () {
  57031. if (sourceSound._isReadyToPlay) {
  57032. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57033. newSound._isReadyToPlay = true;
  57034. if (newSound.autoplay) {
  57035. newSound.play();
  57036. }
  57037. }
  57038. else {
  57039. window.setTimeout(setBufferAndRun, 300);
  57040. }
  57041. };
  57042. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57043. setBufferAndRun();
  57044. }
  57045. if (parsedSound.position) {
  57046. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57047. newSound.setPosition(soundPosition);
  57048. }
  57049. if (parsedSound.isDirectional) {
  57050. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57051. if (parsedSound.localDirectionToMesh) {
  57052. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57053. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57054. }
  57055. }
  57056. if (parsedSound.connectedMeshId) {
  57057. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57058. if (connectedMesh) {
  57059. newSound.attachToMesh(connectedMesh);
  57060. }
  57061. }
  57062. return newSound;
  57063. };
  57064. return Sound;
  57065. }());
  57066. BABYLON.Sound = Sound;
  57067. })(BABYLON || (BABYLON = {}));
  57068. //# sourceMappingURL=babylon.sound.js.map
  57069. var BABYLON;
  57070. (function (BABYLON) {
  57071. var SoundTrack = /** @class */ (function () {
  57072. function SoundTrack(scene, options) {
  57073. this.id = -1;
  57074. this._isMainTrack = false;
  57075. this._isInitialized = false;
  57076. this._scene = scene;
  57077. this.soundCollection = new Array();
  57078. this._options = options;
  57079. if (!this._isMainTrack) {
  57080. this._scene.soundTracks.push(this);
  57081. this.id = this._scene.soundTracks.length - 1;
  57082. }
  57083. }
  57084. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57085. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57086. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57087. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57088. if (this._options) {
  57089. if (this._options.volume) {
  57090. this._outputAudioNode.gain.value = this._options.volume;
  57091. }
  57092. if (this._options.mainTrack) {
  57093. this._isMainTrack = this._options.mainTrack;
  57094. }
  57095. }
  57096. this._isInitialized = true;
  57097. }
  57098. };
  57099. SoundTrack.prototype.dispose = function () {
  57100. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57101. if (this._connectedAnalyser) {
  57102. this._connectedAnalyser.stopDebugCanvas();
  57103. }
  57104. while (this.soundCollection.length) {
  57105. this.soundCollection[0].dispose();
  57106. }
  57107. if (this._outputAudioNode) {
  57108. this._outputAudioNode.disconnect();
  57109. }
  57110. this._outputAudioNode = null;
  57111. }
  57112. };
  57113. SoundTrack.prototype.AddSound = function (sound) {
  57114. if (!this._isInitialized) {
  57115. this._initializeSoundTrackAudioGraph();
  57116. }
  57117. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57118. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57119. }
  57120. if (sound.soundTrackId) {
  57121. if (sound.soundTrackId === -1) {
  57122. this._scene.mainSoundTrack.RemoveSound(sound);
  57123. }
  57124. else {
  57125. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57126. }
  57127. }
  57128. this.soundCollection.push(sound);
  57129. sound.soundTrackId = this.id;
  57130. };
  57131. SoundTrack.prototype.RemoveSound = function (sound) {
  57132. var index = this.soundCollection.indexOf(sound);
  57133. if (index !== -1) {
  57134. this.soundCollection.splice(index, 1);
  57135. }
  57136. };
  57137. SoundTrack.prototype.setVolume = function (newVolume) {
  57138. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57139. this._outputAudioNode.gain.value = newVolume;
  57140. }
  57141. };
  57142. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57143. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57144. for (var i = 0; i < this.soundCollection.length; i++) {
  57145. this.soundCollection[i].switchPanningModelToHRTF();
  57146. }
  57147. }
  57148. };
  57149. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57150. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57151. for (var i = 0; i < this.soundCollection.length; i++) {
  57152. this.soundCollection[i].switchPanningModelToEqualPower();
  57153. }
  57154. }
  57155. };
  57156. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57157. if (this._connectedAnalyser) {
  57158. this._connectedAnalyser.stopDebugCanvas();
  57159. }
  57160. this._connectedAnalyser = analyser;
  57161. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57162. this._outputAudioNode.disconnect();
  57163. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57164. }
  57165. };
  57166. return SoundTrack;
  57167. }());
  57168. BABYLON.SoundTrack = SoundTrack;
  57169. })(BABYLON || (BABYLON = {}));
  57170. //# sourceMappingURL=babylon.soundtrack.js.map
  57171. var BABYLON;
  57172. (function (BABYLON) {
  57173. var Analyser = /** @class */ (function () {
  57174. function Analyser(scene) {
  57175. this.SMOOTHING = 0.75;
  57176. this.FFT_SIZE = 512;
  57177. this.BARGRAPHAMPLITUDE = 256;
  57178. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57179. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57180. this._scene = scene;
  57181. this._audioEngine = BABYLON.Engine.audioEngine;
  57182. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57183. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57184. this._webAudioAnalyser.minDecibels = -140;
  57185. this._webAudioAnalyser.maxDecibels = 0;
  57186. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57187. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57188. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57189. }
  57190. }
  57191. Analyser.prototype.getFrequencyBinCount = function () {
  57192. if (this._audioEngine.canUseWebAudio) {
  57193. return this._webAudioAnalyser.frequencyBinCount;
  57194. }
  57195. else {
  57196. return 0;
  57197. }
  57198. };
  57199. Analyser.prototype.getByteFrequencyData = function () {
  57200. if (this._audioEngine.canUseWebAudio) {
  57201. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57202. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57203. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57204. }
  57205. return this._byteFreqs;
  57206. };
  57207. Analyser.prototype.getByteTimeDomainData = function () {
  57208. if (this._audioEngine.canUseWebAudio) {
  57209. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57210. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57211. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57212. }
  57213. return this._byteTime;
  57214. };
  57215. Analyser.prototype.getFloatFrequencyData = function () {
  57216. if (this._audioEngine.canUseWebAudio) {
  57217. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57218. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57219. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57220. }
  57221. return this._floatFreqs;
  57222. };
  57223. Analyser.prototype.drawDebugCanvas = function () {
  57224. var _this = this;
  57225. if (this._audioEngine.canUseWebAudio) {
  57226. if (!this._debugCanvas) {
  57227. this._debugCanvas = document.createElement("canvas");
  57228. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57229. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57230. this._debugCanvas.style.position = "absolute";
  57231. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57232. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57233. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57234. document.body.appendChild(this._debugCanvas);
  57235. this._registerFunc = function () {
  57236. _this.drawDebugCanvas();
  57237. };
  57238. this._scene.registerBeforeRender(this._registerFunc);
  57239. }
  57240. if (this._registerFunc && this._debugCanvasContext) {
  57241. var workingArray = this.getByteFrequencyData();
  57242. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57243. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57244. // Draw the frequency domain chart.
  57245. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57246. var value = workingArray[i];
  57247. var percent = value / this.BARGRAPHAMPLITUDE;
  57248. var height = this.DEBUGCANVASSIZE.height * percent;
  57249. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57250. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57251. var hue = i / this.getFrequencyBinCount() * 360;
  57252. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57253. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57254. }
  57255. }
  57256. }
  57257. };
  57258. Analyser.prototype.stopDebugCanvas = function () {
  57259. if (this._debugCanvas) {
  57260. if (this._registerFunc) {
  57261. this._scene.unregisterBeforeRender(this._registerFunc);
  57262. this._registerFunc = null;
  57263. }
  57264. document.body.removeChild(this._debugCanvas);
  57265. this._debugCanvas = null;
  57266. this._debugCanvasContext = null;
  57267. }
  57268. };
  57269. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57270. if (this._audioEngine.canUseWebAudio) {
  57271. inputAudioNode.connect(this._webAudioAnalyser);
  57272. this._webAudioAnalyser.connect(outputAudioNode);
  57273. }
  57274. };
  57275. Analyser.prototype.dispose = function () {
  57276. if (this._audioEngine.canUseWebAudio) {
  57277. this._webAudioAnalyser.disconnect();
  57278. }
  57279. };
  57280. return Analyser;
  57281. }());
  57282. BABYLON.Analyser = Analyser;
  57283. })(BABYLON || (BABYLON = {}));
  57284. //# sourceMappingURL=babylon.analyser.js.map
  57285. var BABYLON;
  57286. (function (BABYLON) {
  57287. var CubeTexture = /** @class */ (function (_super) {
  57288. __extends(CubeTexture, _super);
  57289. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57290. if (extensions === void 0) { extensions = null; }
  57291. if (noMipmap === void 0) { noMipmap = false; }
  57292. if (files === void 0) { files = null; }
  57293. if (onLoad === void 0) { onLoad = null; }
  57294. if (onError === void 0) { onError = null; }
  57295. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57296. if (prefiltered === void 0) { prefiltered = false; }
  57297. if (forcedExtension === void 0) { forcedExtension = null; }
  57298. var _this = _super.call(this, scene) || this;
  57299. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57300. /**
  57301. * Gets or sets the center of the bounding box associated with the cube texture
  57302. * It must define where the camera used to render the texture was set
  57303. */
  57304. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57305. _this.name = rootUrl;
  57306. _this.url = rootUrl;
  57307. _this._noMipmap = noMipmap;
  57308. _this.hasAlpha = false;
  57309. _this._format = format;
  57310. _this._prefiltered = prefiltered;
  57311. _this.isCube = true;
  57312. _this._textureMatrix = BABYLON.Matrix.Identity();
  57313. if (prefiltered) {
  57314. _this.gammaSpace = false;
  57315. }
  57316. if (!rootUrl && !files) {
  57317. return _this;
  57318. }
  57319. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57320. var lastDot = rootUrl.lastIndexOf(".");
  57321. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57322. var isDDS = (extension === ".dds");
  57323. if (!files) {
  57324. if (!isDDS && !extensions) {
  57325. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57326. }
  57327. files = [];
  57328. if (extensions) {
  57329. for (var index = 0; index < extensions.length; index++) {
  57330. files.push(rootUrl + extensions[index]);
  57331. }
  57332. }
  57333. }
  57334. _this._files = files;
  57335. if (!_this._texture) {
  57336. if (!scene.useDelayedTextureLoading) {
  57337. if (prefiltered) {
  57338. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57339. }
  57340. else {
  57341. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57342. }
  57343. }
  57344. else {
  57345. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57346. }
  57347. }
  57348. else if (onLoad) {
  57349. if (_this._texture.isReady) {
  57350. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57351. }
  57352. else {
  57353. _this._texture.onLoadedObservable.add(onLoad);
  57354. }
  57355. }
  57356. return _this;
  57357. }
  57358. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57359. get: function () {
  57360. return this._boundingBoxSize;
  57361. },
  57362. /**
  57363. * Gets or sets the size of the bounding box associated with the cube texture
  57364. * When defined, the cubemap will switch to local mode
  57365. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57366. * @example https://www.babylonjs-playground.com/#RNASML
  57367. */
  57368. set: function (value) {
  57369. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57370. return;
  57371. }
  57372. this._boundingBoxSize = value;
  57373. var scene = this.getScene();
  57374. if (scene) {
  57375. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57376. }
  57377. },
  57378. enumerable: true,
  57379. configurable: true
  57380. });
  57381. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57382. var rootUrlKey = "";
  57383. files.forEach(function (url) { return rootUrlKey += url; });
  57384. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57385. };
  57386. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57387. if (forcedExtension === void 0) { forcedExtension = null; }
  57388. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57389. };
  57390. // Methods
  57391. CubeTexture.prototype.delayLoad = function () {
  57392. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57393. return;
  57394. }
  57395. var scene = this.getScene();
  57396. if (!scene) {
  57397. return;
  57398. }
  57399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57400. this._texture = this._getFromCache(this.url, this._noMipmap);
  57401. if (!this._texture) {
  57402. if (this._prefiltered) {
  57403. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57404. }
  57405. else {
  57406. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57407. }
  57408. }
  57409. };
  57410. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57411. return this._textureMatrix;
  57412. };
  57413. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57414. this._textureMatrix = value;
  57415. };
  57416. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57417. var texture = BABYLON.SerializationHelper.Parse(function () {
  57418. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57419. }, parsedTexture, scene);
  57420. // Local Cubemaps
  57421. if (parsedTexture.boundingBoxPosition) {
  57422. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57423. }
  57424. if (parsedTexture.boundingBoxSize) {
  57425. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57426. }
  57427. // Animations
  57428. if (parsedTexture.animations) {
  57429. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57430. var parsedAnimation = parsedTexture.animations[animationIndex];
  57431. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57432. }
  57433. }
  57434. return texture;
  57435. };
  57436. CubeTexture.prototype.clone = function () {
  57437. var _this = this;
  57438. return BABYLON.SerializationHelper.Clone(function () {
  57439. var scene = _this.getScene();
  57440. if (!scene) {
  57441. return _this;
  57442. }
  57443. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57444. }, this);
  57445. };
  57446. return CubeTexture;
  57447. }(BABYLON.BaseTexture));
  57448. BABYLON.CubeTexture = CubeTexture;
  57449. })(BABYLON || (BABYLON = {}));
  57450. //# sourceMappingURL=babylon.cubeTexture.js.map
  57451. var BABYLON;
  57452. (function (BABYLON) {
  57453. var RenderTargetTexture = /** @class */ (function (_super) {
  57454. __extends(RenderTargetTexture, _super);
  57455. /**
  57456. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57457. * or used a shadow, depth texture...
  57458. * @param name The friendly name of the texture
  57459. * @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)
  57460. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57461. * @param generateMipMaps True if mip maps need to be generated after render.
  57462. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57463. * @param type The type of the buffer in the RTT (int, half float, float...)
  57464. * @param isCube True if a cube texture needs to be created
  57465. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57466. * @param generateDepthBuffer True to generate a depth buffer
  57467. * @param generateStencilBuffer True to generate a stencil buffer
  57468. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57469. */
  57470. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57471. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57472. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57473. if (isCube === void 0) { isCube = false; }
  57474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57475. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57476. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57477. if (isMulti === void 0) { isMulti = false; }
  57478. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57479. _this.isCube = isCube;
  57480. /**
  57481. * Use this list to define the list of mesh you want to render.
  57482. */
  57483. _this.renderList = new Array();
  57484. _this.renderParticles = true;
  57485. _this.renderSprites = false;
  57486. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57487. _this.ignoreCameraViewport = false;
  57488. // Events
  57489. /**
  57490. * An event triggered when the texture is unbind.
  57491. * @type {BABYLON.Observable}
  57492. */
  57493. _this.onBeforeBindObservable = new BABYLON.Observable();
  57494. /**
  57495. * An event triggered when the texture is unbind.
  57496. * @type {BABYLON.Observable}
  57497. */
  57498. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57499. /**
  57500. * An event triggered before rendering the texture
  57501. * @type {BABYLON.Observable}
  57502. */
  57503. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57504. /**
  57505. * An event triggered after rendering the texture
  57506. * @type {BABYLON.Observable}
  57507. */
  57508. _this.onAfterRenderObservable = new BABYLON.Observable();
  57509. /**
  57510. * An event triggered after the texture clear
  57511. * @type {BABYLON.Observable}
  57512. */
  57513. _this.onClearObservable = new BABYLON.Observable();
  57514. _this._currentRefreshId = -1;
  57515. _this._refreshRate = 1;
  57516. _this._samples = 1;
  57517. /**
  57518. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57519. * It must define where the camera used to render the texture is set
  57520. */
  57521. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57522. scene = _this.getScene();
  57523. if (!scene) {
  57524. return _this;
  57525. }
  57526. _this._engine = scene.getEngine();
  57527. _this.name = name;
  57528. _this.isRenderTarget = true;
  57529. _this._initialSizeParameter = size;
  57530. _this._processSizeParameter(size);
  57531. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57532. });
  57533. _this._generateMipMaps = generateMipMaps ? true : false;
  57534. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57535. // Rendering groups
  57536. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57537. if (isMulti) {
  57538. return _this;
  57539. }
  57540. _this._renderTargetOptions = {
  57541. generateMipMaps: generateMipMaps,
  57542. type: type,
  57543. samplingMode: samplingMode,
  57544. generateDepthBuffer: generateDepthBuffer,
  57545. generateStencilBuffer: generateStencilBuffer
  57546. };
  57547. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57548. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57549. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57550. }
  57551. if (isCube) {
  57552. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57553. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57554. _this._textureMatrix = BABYLON.Matrix.Identity();
  57555. }
  57556. else {
  57557. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57558. }
  57559. return _this;
  57560. }
  57561. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57562. get: function () {
  57563. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57564. },
  57565. enumerable: true,
  57566. configurable: true
  57567. });
  57568. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57569. get: function () {
  57570. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57571. },
  57572. enumerable: true,
  57573. configurable: true
  57574. });
  57575. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57576. get: function () {
  57577. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57578. },
  57579. enumerable: true,
  57580. configurable: true
  57581. });
  57582. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57583. set: function (callback) {
  57584. if (this._onAfterUnbindObserver) {
  57585. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57586. }
  57587. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57588. },
  57589. enumerable: true,
  57590. configurable: true
  57591. });
  57592. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57593. set: function (callback) {
  57594. if (this._onBeforeRenderObserver) {
  57595. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57596. }
  57597. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57598. },
  57599. enumerable: true,
  57600. configurable: true
  57601. });
  57602. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57603. set: function (callback) {
  57604. if (this._onAfterRenderObserver) {
  57605. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57606. }
  57607. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57608. },
  57609. enumerable: true,
  57610. configurable: true
  57611. });
  57612. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57613. set: function (callback) {
  57614. if (this._onClearObserver) {
  57615. this.onClearObservable.remove(this._onClearObserver);
  57616. }
  57617. this._onClearObserver = this.onClearObservable.add(callback);
  57618. },
  57619. enumerable: true,
  57620. configurable: true
  57621. });
  57622. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57623. get: function () {
  57624. return this._renderTargetOptions;
  57625. },
  57626. enumerable: true,
  57627. configurable: true
  57628. });
  57629. RenderTargetTexture.prototype._onRatioRescale = function () {
  57630. if (this._sizeRatio) {
  57631. this.resize(this._initialSizeParameter);
  57632. }
  57633. };
  57634. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57635. get: function () {
  57636. return this._boundingBoxSize;
  57637. },
  57638. /**
  57639. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57640. * When defined, the cubemap will switch to local mode
  57641. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57642. * @example https://www.babylonjs-playground.com/#RNASML
  57643. */
  57644. set: function (value) {
  57645. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57646. return;
  57647. }
  57648. this._boundingBoxSize = value;
  57649. var scene = this.getScene();
  57650. if (scene) {
  57651. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57652. }
  57653. },
  57654. enumerable: true,
  57655. configurable: true
  57656. });
  57657. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57658. if (size.ratio) {
  57659. this._sizeRatio = size.ratio;
  57660. this._size = {
  57661. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57662. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57663. };
  57664. }
  57665. else {
  57666. this._size = size;
  57667. }
  57668. };
  57669. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57670. get: function () {
  57671. return this._samples;
  57672. },
  57673. set: function (value) {
  57674. if (this._samples === value) {
  57675. return;
  57676. }
  57677. var scene = this.getScene();
  57678. if (!scene) {
  57679. return;
  57680. }
  57681. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57682. },
  57683. enumerable: true,
  57684. configurable: true
  57685. });
  57686. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57687. this._currentRefreshId = -1;
  57688. };
  57689. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57690. get: function () {
  57691. return this._refreshRate;
  57692. },
  57693. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57694. set: function (value) {
  57695. this._refreshRate = value;
  57696. this.resetRefreshCounter();
  57697. },
  57698. enumerable: true,
  57699. configurable: true
  57700. });
  57701. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57702. if (!this._postProcessManager) {
  57703. var scene = this.getScene();
  57704. if (!scene) {
  57705. return;
  57706. }
  57707. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57708. this._postProcesses = new Array();
  57709. }
  57710. this._postProcesses.push(postProcess);
  57711. this._postProcesses[0].autoClear = false;
  57712. };
  57713. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57714. if (!this._postProcesses) {
  57715. return;
  57716. }
  57717. if (dispose) {
  57718. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57719. var postProcess = _a[_i];
  57720. postProcess.dispose();
  57721. }
  57722. }
  57723. this._postProcesses = [];
  57724. };
  57725. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57726. if (!this._postProcesses) {
  57727. return;
  57728. }
  57729. var index = this._postProcesses.indexOf(postProcess);
  57730. if (index === -1) {
  57731. return;
  57732. }
  57733. this._postProcesses.splice(index, 1);
  57734. if (this._postProcesses.length > 0) {
  57735. this._postProcesses[0].autoClear = false;
  57736. }
  57737. };
  57738. RenderTargetTexture.prototype._shouldRender = function () {
  57739. if (this._currentRefreshId === -1) {
  57740. this._currentRefreshId = 1;
  57741. return true;
  57742. }
  57743. if (this.refreshRate === this._currentRefreshId) {
  57744. this._currentRefreshId = 1;
  57745. return true;
  57746. }
  57747. this._currentRefreshId++;
  57748. return false;
  57749. };
  57750. RenderTargetTexture.prototype.getRenderSize = function () {
  57751. if (this._size.width) {
  57752. return this._size.width;
  57753. }
  57754. return this._size;
  57755. };
  57756. RenderTargetTexture.prototype.getRenderWidth = function () {
  57757. if (this._size.width) {
  57758. return this._size.width;
  57759. }
  57760. return this._size;
  57761. };
  57762. RenderTargetTexture.prototype.getRenderHeight = function () {
  57763. if (this._size.width) {
  57764. return this._size.height;
  57765. }
  57766. return this._size;
  57767. };
  57768. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57769. get: function () {
  57770. return true;
  57771. },
  57772. enumerable: true,
  57773. configurable: true
  57774. });
  57775. RenderTargetTexture.prototype.scale = function (ratio) {
  57776. var newSize = this.getRenderSize() * ratio;
  57777. this.resize(newSize);
  57778. };
  57779. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57780. if (this.isCube) {
  57781. return this._textureMatrix;
  57782. }
  57783. return _super.prototype.getReflectionTextureMatrix.call(this);
  57784. };
  57785. RenderTargetTexture.prototype.resize = function (size) {
  57786. this.releaseInternalTexture();
  57787. var scene = this.getScene();
  57788. if (!scene) {
  57789. return;
  57790. }
  57791. this._processSizeParameter(size);
  57792. if (this.isCube) {
  57793. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57794. }
  57795. else {
  57796. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57797. }
  57798. };
  57799. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57800. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57801. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57802. var scene = this.getScene();
  57803. if (!scene) {
  57804. return;
  57805. }
  57806. var engine = scene.getEngine();
  57807. if (this.useCameraPostProcesses !== undefined) {
  57808. useCameraPostProcess = this.useCameraPostProcesses;
  57809. }
  57810. if (this._waitingRenderList) {
  57811. this.renderList = [];
  57812. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57813. var id = this._waitingRenderList[index];
  57814. var mesh_1 = scene.getMeshByID(id);
  57815. if (mesh_1) {
  57816. this.renderList.push(mesh_1);
  57817. }
  57818. }
  57819. delete this._waitingRenderList;
  57820. }
  57821. // Is predicate defined?
  57822. if (this.renderListPredicate) {
  57823. if (this.renderList) {
  57824. this.renderList.splice(0); // Clear previous renderList
  57825. }
  57826. else {
  57827. this.renderList = [];
  57828. }
  57829. var scene = this.getScene();
  57830. if (!scene) {
  57831. return;
  57832. }
  57833. var sceneMeshes = scene.meshes;
  57834. for (var index = 0; index < sceneMeshes.length; index++) {
  57835. var mesh = sceneMeshes[index];
  57836. if (this.renderListPredicate(mesh)) {
  57837. this.renderList.push(mesh);
  57838. }
  57839. }
  57840. }
  57841. this.onBeforeBindObservable.notifyObservers(this);
  57842. // Set custom projection.
  57843. // Needs to be before binding to prevent changing the aspect ratio.
  57844. var camera;
  57845. if (this.activeCamera) {
  57846. camera = this.activeCamera;
  57847. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57848. if (this.activeCamera !== scene.activeCamera) {
  57849. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57850. }
  57851. }
  57852. else {
  57853. camera = scene.activeCamera;
  57854. if (camera) {
  57855. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57856. }
  57857. }
  57858. // Prepare renderingManager
  57859. this._renderingManager.reset();
  57860. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57861. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57862. var sceneRenderId = scene.getRenderId();
  57863. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57864. var mesh = currentRenderList[meshIndex];
  57865. if (mesh) {
  57866. if (!mesh.isReady(this.refreshRate === 0)) {
  57867. this.resetRefreshCounter();
  57868. continue;
  57869. }
  57870. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57871. var isMasked = void 0;
  57872. if (!this.renderList && camera) {
  57873. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57874. }
  57875. else {
  57876. isMasked = false;
  57877. }
  57878. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57879. mesh._activate(sceneRenderId);
  57880. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57881. var subMesh = mesh.subMeshes[subIndex];
  57882. scene._activeIndices.addCount(subMesh.indexCount, false);
  57883. this._renderingManager.dispatch(subMesh, mesh);
  57884. }
  57885. }
  57886. }
  57887. }
  57888. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57889. var particleSystem = scene.particleSystems[particleIndex];
  57890. var emitter = particleSystem.emitter;
  57891. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57892. continue;
  57893. }
  57894. if (currentRenderList.indexOf(emitter) >= 0) {
  57895. this._renderingManager.dispatchParticles(particleSystem);
  57896. }
  57897. }
  57898. if (this.isCube) {
  57899. for (var face = 0; face < 6; face++) {
  57900. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57901. scene.incrementRenderId();
  57902. scene.resetCachedMaterial();
  57903. }
  57904. }
  57905. else {
  57906. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57907. }
  57908. this.onAfterUnbindObservable.notifyObservers(this);
  57909. if (scene.activeCamera) {
  57910. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57911. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57912. }
  57913. engine.setViewport(scene.activeCamera.viewport);
  57914. }
  57915. scene.resetCachedMaterial();
  57916. };
  57917. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57918. var minimum = 128;
  57919. var x = renderDimension * scale;
  57920. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57921. // Ensure we don't exceed the render dimension (while staying POT)
  57922. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57923. };
  57924. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57925. var _this = this;
  57926. if (!this._texture) {
  57927. return;
  57928. }
  57929. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57930. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57931. });
  57932. };
  57933. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57934. var scene = this.getScene();
  57935. if (!scene) {
  57936. return;
  57937. }
  57938. var engine = scene.getEngine();
  57939. if (!this._texture) {
  57940. return;
  57941. }
  57942. // Bind
  57943. if (this._postProcessManager) {
  57944. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57945. }
  57946. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57947. if (this._texture) {
  57948. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57949. }
  57950. }
  57951. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57952. // Clear
  57953. if (this.onClearObservable.hasObservers()) {
  57954. this.onClearObservable.notifyObservers(engine);
  57955. }
  57956. else {
  57957. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57958. }
  57959. if (!this._doNotChangeAspectRatio) {
  57960. scene.updateTransformMatrix(true);
  57961. }
  57962. // Render
  57963. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57964. if (this._postProcessManager) {
  57965. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57966. }
  57967. else if (useCameraPostProcess) {
  57968. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57969. }
  57970. if (!this._doNotChangeAspectRatio) {
  57971. scene.updateTransformMatrix(true);
  57972. }
  57973. // Dump ?
  57974. if (dumpForDebug) {
  57975. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57976. }
  57977. // Unbind
  57978. if (!this.isCube || faceIndex === 5) {
  57979. if (this.isCube) {
  57980. if (faceIndex === 5) {
  57981. engine.generateMipMapsForCubemap(this._texture);
  57982. }
  57983. }
  57984. this.unbindFrameBuffer(engine, faceIndex);
  57985. }
  57986. else {
  57987. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57988. }
  57989. };
  57990. /**
  57991. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57992. * This allowed control for front to back rendering or reversly depending of the special needs.
  57993. *
  57994. * @param renderingGroupId The rendering group id corresponding to its index
  57995. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57996. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57997. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57998. */
  57999. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58000. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58001. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58002. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58003. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58004. };
  58005. /**
  58006. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58007. *
  58008. * @param renderingGroupId The rendering group id corresponding to its index
  58009. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58010. */
  58011. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58012. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58013. };
  58014. RenderTargetTexture.prototype.clone = function () {
  58015. var textureSize = this.getSize();
  58016. 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);
  58017. // Base texture
  58018. newTexture.hasAlpha = this.hasAlpha;
  58019. newTexture.level = this.level;
  58020. // RenderTarget Texture
  58021. newTexture.coordinatesMode = this.coordinatesMode;
  58022. if (this.renderList) {
  58023. newTexture.renderList = this.renderList.slice(0);
  58024. }
  58025. return newTexture;
  58026. };
  58027. RenderTargetTexture.prototype.serialize = function () {
  58028. if (!this.name) {
  58029. return null;
  58030. }
  58031. var serializationObject = _super.prototype.serialize.call(this);
  58032. serializationObject.renderTargetSize = this.getRenderSize();
  58033. serializationObject.renderList = [];
  58034. if (this.renderList) {
  58035. for (var index = 0; index < this.renderList.length; index++) {
  58036. serializationObject.renderList.push(this.renderList[index].id);
  58037. }
  58038. }
  58039. return serializationObject;
  58040. };
  58041. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58042. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58043. var objBuffer = this.getInternalTexture();
  58044. var scene = this.getScene();
  58045. if (objBuffer && scene) {
  58046. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58047. }
  58048. };
  58049. RenderTargetTexture.prototype.dispose = function () {
  58050. if (this._postProcessManager) {
  58051. this._postProcessManager.dispose();
  58052. this._postProcessManager = null;
  58053. }
  58054. this.clearPostProcesses(true);
  58055. if (this._resizeObserver) {
  58056. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58057. this._resizeObserver = null;
  58058. }
  58059. this.renderList = null;
  58060. // Remove from custom render targets
  58061. var scene = this.getScene();
  58062. if (!scene) {
  58063. return;
  58064. }
  58065. var index = scene.customRenderTargets.indexOf(this);
  58066. if (index >= 0) {
  58067. scene.customRenderTargets.splice(index, 1);
  58068. }
  58069. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58070. var camera = _a[_i];
  58071. index = camera.customRenderTargets.indexOf(this);
  58072. if (index >= 0) {
  58073. camera.customRenderTargets.splice(index, 1);
  58074. }
  58075. }
  58076. _super.prototype.dispose.call(this);
  58077. };
  58078. RenderTargetTexture.prototype._rebuild = function () {
  58079. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58080. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58081. }
  58082. if (this._postProcessManager) {
  58083. this._postProcessManager._rebuild();
  58084. }
  58085. };
  58086. /**
  58087. * Clear the info related to rendering groups preventing retention point in material dispose.
  58088. */
  58089. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58090. if (this._renderingManager) {
  58091. this._renderingManager.freeRenderingGroups();
  58092. }
  58093. };
  58094. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58095. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58096. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58097. return RenderTargetTexture;
  58098. }(BABYLON.Texture));
  58099. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58100. })(BABYLON || (BABYLON = {}));
  58101. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58102. var BABYLON;
  58103. (function (BABYLON) {
  58104. ;
  58105. var MultiRenderTarget = /** @class */ (function (_super) {
  58106. __extends(MultiRenderTarget, _super);
  58107. function MultiRenderTarget(name, size, count, scene, options) {
  58108. var _this = this;
  58109. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58110. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58111. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58112. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58113. _this._engine = scene.getEngine();
  58114. if (!_this.isSupported) {
  58115. _this.dispose();
  58116. return;
  58117. }
  58118. var types = [];
  58119. var samplingModes = [];
  58120. for (var i = 0; i < count; i++) {
  58121. if (options && options.types && options.types[i] !== undefined) {
  58122. types.push(options.types[i]);
  58123. }
  58124. else {
  58125. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58126. }
  58127. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58128. samplingModes.push(options.samplingModes[i]);
  58129. }
  58130. else {
  58131. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58132. }
  58133. }
  58134. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58135. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58136. _this._size = size;
  58137. _this._multiRenderTargetOptions = {
  58138. samplingModes: samplingModes,
  58139. generateMipMaps: generateMipMaps,
  58140. generateDepthBuffer: generateDepthBuffer,
  58141. generateStencilBuffer: generateStencilBuffer,
  58142. generateDepthTexture: generateDepthTexture,
  58143. types: types,
  58144. textureCount: count
  58145. };
  58146. _this._createInternalTextures();
  58147. _this._createTextures();
  58148. return _this;
  58149. }
  58150. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58151. get: function () {
  58152. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58153. },
  58154. enumerable: true,
  58155. configurable: true
  58156. });
  58157. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58158. get: function () {
  58159. return this._textures;
  58160. },
  58161. enumerable: true,
  58162. configurable: true
  58163. });
  58164. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58165. get: function () {
  58166. return this._textures[this._textures.length - 1];
  58167. },
  58168. enumerable: true,
  58169. configurable: true
  58170. });
  58171. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58172. set: function (wrap) {
  58173. if (this._textures) {
  58174. for (var i = 0; i < this._textures.length; i++) {
  58175. this._textures[i].wrapU = wrap;
  58176. }
  58177. }
  58178. },
  58179. enumerable: true,
  58180. configurable: true
  58181. });
  58182. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58183. set: function (wrap) {
  58184. if (this._textures) {
  58185. for (var i = 0; i < this._textures.length; i++) {
  58186. this._textures[i].wrapV = wrap;
  58187. }
  58188. }
  58189. },
  58190. enumerable: true,
  58191. configurable: true
  58192. });
  58193. MultiRenderTarget.prototype._rebuild = function () {
  58194. this.releaseInternalTextures();
  58195. this._createInternalTextures();
  58196. for (var i = 0; i < this._internalTextures.length; i++) {
  58197. var texture = this._textures[i];
  58198. texture._texture = this._internalTextures[i];
  58199. }
  58200. // Keeps references to frame buffer and stencil/depth buffer
  58201. this._texture = this._internalTextures[0];
  58202. };
  58203. MultiRenderTarget.prototype._createInternalTextures = function () {
  58204. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58205. };
  58206. MultiRenderTarget.prototype._createTextures = function () {
  58207. this._textures = [];
  58208. for (var i = 0; i < this._internalTextures.length; i++) {
  58209. var texture = new BABYLON.Texture(null, this.getScene());
  58210. texture._texture = this._internalTextures[i];
  58211. this._textures.push(texture);
  58212. }
  58213. // Keeps references to frame buffer and stencil/depth buffer
  58214. this._texture = this._internalTextures[0];
  58215. };
  58216. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58217. get: function () {
  58218. return this._samples;
  58219. },
  58220. set: function (value) {
  58221. if (this._samples === value) {
  58222. return;
  58223. }
  58224. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58225. },
  58226. enumerable: true,
  58227. configurable: true
  58228. });
  58229. MultiRenderTarget.prototype.resize = function (size) {
  58230. this.releaseInternalTextures();
  58231. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58232. this._createInternalTextures();
  58233. };
  58234. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58235. var _this = this;
  58236. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58237. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58238. });
  58239. };
  58240. MultiRenderTarget.prototype.dispose = function () {
  58241. this.releaseInternalTextures();
  58242. _super.prototype.dispose.call(this);
  58243. };
  58244. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58245. if (!this._internalTextures) {
  58246. return;
  58247. }
  58248. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58249. if (this._internalTextures[i] !== undefined) {
  58250. this._internalTextures[i].dispose();
  58251. this._internalTextures.splice(i, 1);
  58252. }
  58253. }
  58254. };
  58255. return MultiRenderTarget;
  58256. }(BABYLON.RenderTargetTexture));
  58257. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58258. })(BABYLON || (BABYLON = {}));
  58259. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58260. var BABYLON;
  58261. (function (BABYLON) {
  58262. var MirrorTexture = /** @class */ (function (_super) {
  58263. __extends(MirrorTexture, _super);
  58264. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58265. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58267. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58268. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58269. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58270. _this._transformMatrix = BABYLON.Matrix.Zero();
  58271. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58272. _this._adaptiveBlurKernel = 0;
  58273. _this._blurKernelX = 0;
  58274. _this._blurKernelY = 0;
  58275. _this._blurRatio = 1.0;
  58276. _this.ignoreCameraViewport = true;
  58277. _this.onBeforeRenderObservable.add(function () {
  58278. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58279. _this._savedViewMatrix = scene.getViewMatrix();
  58280. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58281. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58282. scene.clipPlane = _this.mirrorPlane;
  58283. scene.getEngine().cullBackFaces = false;
  58284. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58285. });
  58286. _this.onAfterRenderObservable.add(function () {
  58287. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58288. scene.getEngine().cullBackFaces = true;
  58289. scene._mirroredCameraPosition = null;
  58290. delete scene.clipPlane;
  58291. });
  58292. return _this;
  58293. }
  58294. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58295. get: function () {
  58296. return this._blurRatio;
  58297. },
  58298. set: function (value) {
  58299. if (this._blurRatio === value) {
  58300. return;
  58301. }
  58302. this._blurRatio = value;
  58303. this._preparePostProcesses();
  58304. },
  58305. enumerable: true,
  58306. configurable: true
  58307. });
  58308. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58309. set: function (value) {
  58310. this._adaptiveBlurKernel = value;
  58311. this._autoComputeBlurKernel();
  58312. },
  58313. enumerable: true,
  58314. configurable: true
  58315. });
  58316. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58317. set: function (value) {
  58318. this.blurKernelX = value;
  58319. this.blurKernelY = value;
  58320. },
  58321. enumerable: true,
  58322. configurable: true
  58323. });
  58324. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58325. get: function () {
  58326. return this._blurKernelX;
  58327. },
  58328. set: function (value) {
  58329. if (this._blurKernelX === value) {
  58330. return;
  58331. }
  58332. this._blurKernelX = value;
  58333. this._preparePostProcesses();
  58334. },
  58335. enumerable: true,
  58336. configurable: true
  58337. });
  58338. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58339. get: function () {
  58340. return this._blurKernelY;
  58341. },
  58342. set: function (value) {
  58343. if (this._blurKernelY === value) {
  58344. return;
  58345. }
  58346. this._blurKernelY = value;
  58347. this._preparePostProcesses();
  58348. },
  58349. enumerable: true,
  58350. configurable: true
  58351. });
  58352. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58353. var engine = this.getScene().getEngine();
  58354. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58355. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58356. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58357. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58358. };
  58359. MirrorTexture.prototype._onRatioRescale = function () {
  58360. if (this._sizeRatio) {
  58361. this.resize(this._initialSizeParameter);
  58362. if (!this._adaptiveBlurKernel) {
  58363. this._preparePostProcesses();
  58364. }
  58365. }
  58366. if (this._adaptiveBlurKernel) {
  58367. this._autoComputeBlurKernel();
  58368. }
  58369. };
  58370. MirrorTexture.prototype._preparePostProcesses = function () {
  58371. this.clearPostProcesses(true);
  58372. if (this._blurKernelX && this._blurKernelY) {
  58373. var engine = this.getScene().getEngine();
  58374. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58375. 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);
  58376. this._blurX.autoClear = false;
  58377. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58378. this._blurX.inputTexture = this._texture;
  58379. }
  58380. else {
  58381. this._blurX.alwaysForcePOT = true;
  58382. }
  58383. 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);
  58384. this._blurY.autoClear = false;
  58385. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58386. this.addPostProcess(this._blurX);
  58387. this.addPostProcess(this._blurY);
  58388. }
  58389. else {
  58390. if (this._blurY) {
  58391. this.removePostProcess(this._blurY);
  58392. this._blurY.dispose();
  58393. this._blurY = null;
  58394. }
  58395. if (this._blurX) {
  58396. this.removePostProcess(this._blurX);
  58397. this._blurX.dispose();
  58398. this._blurX = null;
  58399. }
  58400. }
  58401. };
  58402. MirrorTexture.prototype.clone = function () {
  58403. var scene = this.getScene();
  58404. if (!scene) {
  58405. return this;
  58406. }
  58407. var textureSize = this.getSize();
  58408. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58409. // Base texture
  58410. newTexture.hasAlpha = this.hasAlpha;
  58411. newTexture.level = this.level;
  58412. // Mirror Texture
  58413. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58414. if (this.renderList) {
  58415. newTexture.renderList = this.renderList.slice(0);
  58416. }
  58417. return newTexture;
  58418. };
  58419. MirrorTexture.prototype.serialize = function () {
  58420. if (!this.name) {
  58421. return null;
  58422. }
  58423. var serializationObject = _super.prototype.serialize.call(this);
  58424. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58425. return serializationObject;
  58426. };
  58427. return MirrorTexture;
  58428. }(BABYLON.RenderTargetTexture));
  58429. BABYLON.MirrorTexture = MirrorTexture;
  58430. })(BABYLON || (BABYLON = {}));
  58431. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58432. var BABYLON;
  58433. (function (BABYLON) {
  58434. /**
  58435. * Creates a refraction texture used by refraction channel of the standard material.
  58436. * @param name the texture name
  58437. * @param size size of the underlying texture
  58438. * @param scene root scene
  58439. */
  58440. var RefractionTexture = /** @class */ (function (_super) {
  58441. __extends(RefractionTexture, _super);
  58442. function RefractionTexture(name, size, scene, generateMipMaps) {
  58443. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58444. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58445. _this.depth = 2.0;
  58446. _this.onBeforeRenderObservable.add(function () {
  58447. scene.clipPlane = _this.refractionPlane;
  58448. });
  58449. _this.onAfterRenderObservable.add(function () {
  58450. delete scene.clipPlane;
  58451. });
  58452. return _this;
  58453. }
  58454. RefractionTexture.prototype.clone = function () {
  58455. var scene = this.getScene();
  58456. if (!scene) {
  58457. return this;
  58458. }
  58459. var textureSize = this.getSize();
  58460. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58461. // Base texture
  58462. newTexture.hasAlpha = this.hasAlpha;
  58463. newTexture.level = this.level;
  58464. // Refraction Texture
  58465. newTexture.refractionPlane = this.refractionPlane.clone();
  58466. if (this.renderList) {
  58467. newTexture.renderList = this.renderList.slice(0);
  58468. }
  58469. newTexture.depth = this.depth;
  58470. return newTexture;
  58471. };
  58472. RefractionTexture.prototype.serialize = function () {
  58473. if (!this.name) {
  58474. return null;
  58475. }
  58476. var serializationObject = _super.prototype.serialize.call(this);
  58477. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58478. serializationObject.depth = this.depth;
  58479. return serializationObject;
  58480. };
  58481. return RefractionTexture;
  58482. }(BABYLON.RenderTargetTexture));
  58483. BABYLON.RefractionTexture = RefractionTexture;
  58484. })(BABYLON || (BABYLON = {}));
  58485. //# sourceMappingURL=babylon.refractionTexture.js.map
  58486. var BABYLON;
  58487. (function (BABYLON) {
  58488. var DynamicTexture = /** @class */ (function (_super) {
  58489. __extends(DynamicTexture, _super);
  58490. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58491. if (scene === void 0) { scene = null; }
  58492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58493. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58494. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58495. _this.name = name;
  58496. _this._engine = _this.getScene().getEngine();
  58497. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58498. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58499. _this._generateMipMaps = generateMipMaps;
  58500. if (options.getContext) {
  58501. _this._canvas = options;
  58502. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58503. }
  58504. else {
  58505. _this._canvas = document.createElement("canvas");
  58506. if (options.width) {
  58507. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58508. }
  58509. else {
  58510. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58511. }
  58512. }
  58513. var textureSize = _this.getSize();
  58514. _this._canvas.width = textureSize.width;
  58515. _this._canvas.height = textureSize.height;
  58516. _this._context = _this._canvas.getContext("2d");
  58517. return _this;
  58518. }
  58519. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58520. get: function () {
  58521. return true;
  58522. },
  58523. enumerable: true,
  58524. configurable: true
  58525. });
  58526. DynamicTexture.prototype._recreate = function (textureSize) {
  58527. this._canvas.width = textureSize.width;
  58528. this._canvas.height = textureSize.height;
  58529. this.releaseInternalTexture();
  58530. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58531. };
  58532. DynamicTexture.prototype.scale = function (ratio) {
  58533. var textureSize = this.getSize();
  58534. textureSize.width *= ratio;
  58535. textureSize.height *= ratio;
  58536. this._recreate(textureSize);
  58537. };
  58538. DynamicTexture.prototype.scaleTo = function (width, height) {
  58539. var textureSize = this.getSize();
  58540. textureSize.width = width;
  58541. textureSize.height = height;
  58542. this._recreate(textureSize);
  58543. };
  58544. DynamicTexture.prototype.getContext = function () {
  58545. return this._context;
  58546. };
  58547. DynamicTexture.prototype.clear = function () {
  58548. var size = this.getSize();
  58549. this._context.fillRect(0, 0, size.width, size.height);
  58550. };
  58551. DynamicTexture.prototype.update = function (invertY) {
  58552. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58553. };
  58554. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58555. if (update === void 0) { update = true; }
  58556. var size = this.getSize();
  58557. if (clearColor) {
  58558. this._context.fillStyle = clearColor;
  58559. this._context.fillRect(0, 0, size.width, size.height);
  58560. }
  58561. this._context.font = font;
  58562. if (x === null || x === undefined) {
  58563. var textSize = this._context.measureText(text);
  58564. x = (size.width - textSize.width) / 2;
  58565. }
  58566. if (y === null || y === undefined) {
  58567. var fontSize = parseInt((font.replace(/\D/g, '')));
  58568. ;
  58569. y = (size.height / 2) + (fontSize / 3.65);
  58570. }
  58571. this._context.fillStyle = color;
  58572. this._context.fillText(text, x, y);
  58573. if (update) {
  58574. this.update(invertY);
  58575. }
  58576. };
  58577. DynamicTexture.prototype.clone = function () {
  58578. var scene = this.getScene();
  58579. if (!scene) {
  58580. return this;
  58581. }
  58582. var textureSize = this.getSize();
  58583. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58584. // Base texture
  58585. newTexture.hasAlpha = this.hasAlpha;
  58586. newTexture.level = this.level;
  58587. // Dynamic Texture
  58588. newTexture.wrapU = this.wrapU;
  58589. newTexture.wrapV = this.wrapV;
  58590. return newTexture;
  58591. };
  58592. DynamicTexture.prototype._rebuild = function () {
  58593. this.update();
  58594. };
  58595. return DynamicTexture;
  58596. }(BABYLON.Texture));
  58597. BABYLON.DynamicTexture = DynamicTexture;
  58598. })(BABYLON || (BABYLON = {}));
  58599. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58600. var BABYLON;
  58601. (function (BABYLON) {
  58602. var VideoTexture = /** @class */ (function (_super) {
  58603. __extends(VideoTexture, _super);
  58604. /**
  58605. * Creates a video texture.
  58606. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58607. * @param {string | null} name optional name, will detect from video source, if not defined
  58608. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58609. * @param {BABYLON.Scene} scene is obviously the current scene.
  58610. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58611. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58612. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58613. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58614. */
  58615. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58616. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58617. if (invertY === void 0) { invertY = false; }
  58618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58619. if (settings === void 0) { settings = {
  58620. autoPlay: true,
  58621. loop: true,
  58622. autoUpdateTexture: true,
  58623. }; }
  58624. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58625. _this._createInternalTexture = function () {
  58626. if (_this._texture != null) {
  58627. return;
  58628. }
  58629. if (!_this._engine.needPOTTextures ||
  58630. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58631. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58632. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58633. }
  58634. else {
  58635. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58636. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58637. _this._generateMipMaps = false;
  58638. }
  58639. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58640. _this._texture.isReady = true;
  58641. _this._updateInternalTexture();
  58642. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58643. _this.onLoadObservable.notifyObservers(_this);
  58644. }
  58645. };
  58646. _this.reset = function () {
  58647. if (_this._texture == null) {
  58648. return;
  58649. }
  58650. _this._texture.dispose();
  58651. _this._texture = null;
  58652. };
  58653. _this._updateInternalTexture = function (e) {
  58654. if (_this._texture == null || !_this._texture.isReady) {
  58655. return;
  58656. }
  58657. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58658. return;
  58659. }
  58660. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58661. };
  58662. _this._engine = _this.getScene().getEngine();
  58663. _this._generateMipMaps = generateMipMaps;
  58664. _this._samplingMode = samplingMode;
  58665. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58666. _this.name = name || _this._getName(src);
  58667. _this.video = _this._getVideo(src);
  58668. if (settings.autoPlay !== undefined) {
  58669. _this.video.autoplay = settings.autoPlay;
  58670. }
  58671. if (settings.loop !== undefined) {
  58672. _this.video.loop = settings.loop;
  58673. }
  58674. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58675. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58676. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58677. _this.video.addEventListener("emptied", _this.reset);
  58678. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58679. _this._createInternalTexture();
  58680. }
  58681. return _this;
  58682. }
  58683. VideoTexture.prototype._getName = function (src) {
  58684. if (src instanceof HTMLVideoElement) {
  58685. return src.currentSrc;
  58686. }
  58687. if (typeof src === "object") {
  58688. return src.toString();
  58689. }
  58690. return src;
  58691. };
  58692. ;
  58693. VideoTexture.prototype._getVideo = function (src) {
  58694. if (src instanceof HTMLVideoElement) {
  58695. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58696. return src;
  58697. }
  58698. var video = document.createElement("video");
  58699. if (typeof src === "string") {
  58700. BABYLON.Tools.SetCorsBehavior(src, video);
  58701. video.src = src;
  58702. }
  58703. else {
  58704. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58705. src.forEach(function (url) {
  58706. var source = document.createElement("source");
  58707. source.src = url;
  58708. video.appendChild(source);
  58709. });
  58710. }
  58711. return video;
  58712. };
  58713. ;
  58714. /**
  58715. * Internal method to initiate `update`.
  58716. */
  58717. VideoTexture.prototype._rebuild = function () {
  58718. this.update();
  58719. };
  58720. /**
  58721. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58722. */
  58723. VideoTexture.prototype.update = function () {
  58724. if (!this.autoUpdateTexture) {
  58725. // Expecting user to call `updateTexture` manually
  58726. return;
  58727. }
  58728. this.updateTexture(true);
  58729. };
  58730. /**
  58731. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58732. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58733. */
  58734. VideoTexture.prototype.updateTexture = function (isVisible) {
  58735. if (!isVisible) {
  58736. return;
  58737. }
  58738. if (this.video.paused) {
  58739. return;
  58740. }
  58741. this._updateInternalTexture();
  58742. };
  58743. /**
  58744. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58745. * @param url New url.
  58746. */
  58747. VideoTexture.prototype.updateURL = function (url) {
  58748. this.video.src = url;
  58749. };
  58750. VideoTexture.prototype.dispose = function () {
  58751. _super.prototype.dispose.call(this);
  58752. this.video.removeEventListener("canplay", this._createInternalTexture);
  58753. this.video.removeEventListener("paused", this._updateInternalTexture);
  58754. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58755. this.video.removeEventListener("emptied", this.reset);
  58756. this.video.pause();
  58757. };
  58758. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58759. var video = document.createElement("video");
  58760. var constraintsDeviceId;
  58761. if (constraints && constraints.deviceId) {
  58762. constraintsDeviceId = {
  58763. exact: constraints.deviceId,
  58764. };
  58765. }
  58766. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58767. if (navigator.mediaDevices) {
  58768. navigator.mediaDevices.getUserMedia({ video: constraints })
  58769. .then(function (stream) {
  58770. if (video.mozSrcObject !== undefined) {
  58771. // hack for Firefox < 19
  58772. video.mozSrcObject = stream;
  58773. }
  58774. else {
  58775. video.srcObject = stream;
  58776. }
  58777. var onPlaying = function () {
  58778. if (onReady) {
  58779. onReady(new VideoTexture("video", video, scene, true, true));
  58780. }
  58781. video.removeEventListener("playing", onPlaying);
  58782. };
  58783. video.addEventListener("playing", onPlaying);
  58784. video.play();
  58785. })
  58786. .catch(function (err) {
  58787. BABYLON.Tools.Error(err.name);
  58788. });
  58789. }
  58790. else {
  58791. navigator.getUserMedia =
  58792. navigator.getUserMedia ||
  58793. navigator.webkitGetUserMedia ||
  58794. navigator.mozGetUserMedia ||
  58795. navigator.msGetUserMedia;
  58796. if (navigator.getUserMedia) {
  58797. navigator.getUserMedia({
  58798. video: {
  58799. deviceId: constraintsDeviceId,
  58800. width: {
  58801. min: (constraints && constraints.minWidth) || 256,
  58802. max: (constraints && constraints.maxWidth) || 640,
  58803. },
  58804. height: {
  58805. min: (constraints && constraints.minHeight) || 256,
  58806. max: (constraints && constraints.maxHeight) || 480,
  58807. },
  58808. },
  58809. }, function (stream) {
  58810. if (video.mozSrcObject !== undefined) {
  58811. // hack for Firefox < 19
  58812. video.mozSrcObject = stream;
  58813. }
  58814. else {
  58815. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58816. }
  58817. video.play();
  58818. if (onReady) {
  58819. onReady(new VideoTexture("video", video, scene, true, true));
  58820. }
  58821. }, function (e) {
  58822. BABYLON.Tools.Error(e.name);
  58823. });
  58824. }
  58825. }
  58826. };
  58827. return VideoTexture;
  58828. }(BABYLON.Texture));
  58829. BABYLON.VideoTexture = VideoTexture;
  58830. })(BABYLON || (BABYLON = {}));
  58831. //# sourceMappingURL=babylon.videoTexture.js.map
  58832. var BABYLON;
  58833. (function (BABYLON) {
  58834. var RawTexture = /** @class */ (function (_super) {
  58835. __extends(RawTexture, _super);
  58836. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58837. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58838. if (invertY === void 0) { invertY = false; }
  58839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58840. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58841. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58842. _this.format = format;
  58843. _this._engine = scene.getEngine();
  58844. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58845. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58846. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58847. return _this;
  58848. }
  58849. RawTexture.prototype.update = function (data) {
  58850. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58851. };
  58852. // Statics
  58853. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58854. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58855. if (invertY === void 0) { invertY = false; }
  58856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58857. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58858. };
  58859. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58860. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58861. if (invertY === void 0) { invertY = false; }
  58862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58863. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58864. };
  58865. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58866. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58867. if (invertY === void 0) { invertY = false; }
  58868. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58869. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58870. };
  58871. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58872. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58873. if (invertY === void 0) { invertY = false; }
  58874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58875. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58876. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58877. };
  58878. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58879. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58880. if (invertY === void 0) { invertY = false; }
  58881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58882. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58883. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58884. };
  58885. return RawTexture;
  58886. }(BABYLON.Texture));
  58887. BABYLON.RawTexture = RawTexture;
  58888. })(BABYLON || (BABYLON = {}));
  58889. //# sourceMappingURL=babylon.rawTexture.js.map
  58890. var BABYLON;
  58891. (function (BABYLON) {
  58892. /**
  58893. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58894. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58895. */
  58896. var PostProcess = /** @class */ (function () {
  58897. /**
  58898. * Creates a new instance of @see PostProcess
  58899. * @param name The name of the PostProcess.
  58900. * @param fragmentUrl The url of the fragment shader to be used.
  58901. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58902. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58903. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58904. * @param camera The camera to apply the render pass to.
  58905. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58906. * @param engine The engine which the post process will be applied. (default: current engine)
  58907. * @param reusable If the post process can be reused on the same frame. (default: false)
  58908. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58909. * @param textureType Type of textures used when performing the post process. (default: 0)
  58910. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58911. * @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
  58912. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58913. */
  58914. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58916. if (defines === void 0) { defines = null; }
  58917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58918. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58919. if (blockCompilation === void 0) { blockCompilation = false; }
  58920. this.name = name;
  58921. /**
  58922. * Width of the texture to apply the post process on
  58923. */
  58924. this.width = -1;
  58925. /**
  58926. * Height of the texture to apply the post process on
  58927. */
  58928. this.height = -1;
  58929. /**
  58930. * If the buffer needs to be cleared before applying the post process. (default: true)
  58931. * Should be set to false if shader will overwrite all previous pixels.
  58932. */
  58933. this.autoClear = true;
  58934. /**
  58935. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58936. */
  58937. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58938. /**
  58939. * Animations to be used for the post processing
  58940. */
  58941. this.animations = new Array();
  58942. /**
  58943. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58944. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58945. */
  58946. this.enablePixelPerfectMode = false;
  58947. /**
  58948. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58949. */
  58950. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58951. /**
  58952. * Force textures to be a power of two (default: false)
  58953. */
  58954. this.alwaysForcePOT = false;
  58955. /**
  58956. * Number of sample textures (default: 1)
  58957. */
  58958. this.samples = 1;
  58959. /**
  58960. * Modify the scale of the post process to be the same as the viewport (default: false)
  58961. */
  58962. this.adaptScaleToCurrentViewport = false;
  58963. this._reusable = false;
  58964. /**
  58965. * Smart array of input and output textures for the post process.
  58966. */
  58967. this._textures = new BABYLON.SmartArray(2);
  58968. /**
  58969. * The index in _textures that corresponds to the output texture.
  58970. */
  58971. this._currentRenderTextureInd = 0;
  58972. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58973. this._texelSize = BABYLON.Vector2.Zero();
  58974. // Events
  58975. /**
  58976. * An event triggered when the postprocess is activated.
  58977. * @type {BABYLON.Observable}
  58978. */
  58979. this.onActivateObservable = new BABYLON.Observable();
  58980. /**
  58981. * An event triggered when the postprocess changes its size.
  58982. * @type {BABYLON.Observable}
  58983. */
  58984. this.onSizeChangedObservable = new BABYLON.Observable();
  58985. /**
  58986. * An event triggered when the postprocess applies its effect.
  58987. * @type {BABYLON.Observable}
  58988. */
  58989. this.onApplyObservable = new BABYLON.Observable();
  58990. /**
  58991. * An event triggered before rendering the postprocess
  58992. * @type {BABYLON.Observable}
  58993. */
  58994. this.onBeforeRenderObservable = new BABYLON.Observable();
  58995. /**
  58996. * An event triggered after rendering the postprocess
  58997. * @type {BABYLON.Observable}
  58998. */
  58999. this.onAfterRenderObservable = new BABYLON.Observable();
  59000. if (camera != null) {
  59001. this._camera = camera;
  59002. this._scene = camera.getScene();
  59003. camera.attachPostProcess(this);
  59004. this._engine = this._scene.getEngine();
  59005. this._scene.postProcesses.push(this);
  59006. }
  59007. else if (engine) {
  59008. this._engine = engine;
  59009. this._engine.postProcesses.push(this);
  59010. }
  59011. this._options = options;
  59012. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59013. this._reusable = reusable || false;
  59014. this._textureType = textureType;
  59015. this._samplers = samplers || [];
  59016. this._samplers.push("textureSampler");
  59017. this._fragmentUrl = fragmentUrl;
  59018. this._vertexUrl = vertexUrl;
  59019. this._parameters = parameters || [];
  59020. this._parameters.push("scale");
  59021. this._indexParameters = indexParameters;
  59022. if (!blockCompilation) {
  59023. this.updateEffect(defines);
  59024. }
  59025. }
  59026. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59027. /**
  59028. * A function that is added to the onActivateObservable
  59029. */
  59030. set: function (callback) {
  59031. if (this._onActivateObserver) {
  59032. this.onActivateObservable.remove(this._onActivateObserver);
  59033. }
  59034. if (callback) {
  59035. this._onActivateObserver = this.onActivateObservable.add(callback);
  59036. }
  59037. },
  59038. enumerable: true,
  59039. configurable: true
  59040. });
  59041. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59042. /**
  59043. * A function that is added to the onSizeChangedObservable
  59044. */
  59045. set: function (callback) {
  59046. if (this._onSizeChangedObserver) {
  59047. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59048. }
  59049. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59050. },
  59051. enumerable: true,
  59052. configurable: true
  59053. });
  59054. Object.defineProperty(PostProcess.prototype, "onApply", {
  59055. /**
  59056. * A function that is added to the onApplyObservable
  59057. */
  59058. set: function (callback) {
  59059. if (this._onApplyObserver) {
  59060. this.onApplyObservable.remove(this._onApplyObserver);
  59061. }
  59062. this._onApplyObserver = this.onApplyObservable.add(callback);
  59063. },
  59064. enumerable: true,
  59065. configurable: true
  59066. });
  59067. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59068. /**
  59069. * A function that is added to the onBeforeRenderObservable
  59070. */
  59071. set: function (callback) {
  59072. if (this._onBeforeRenderObserver) {
  59073. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59074. }
  59075. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59076. },
  59077. enumerable: true,
  59078. configurable: true
  59079. });
  59080. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59081. /**
  59082. * A function that is added to the onAfterRenderObservable
  59083. */
  59084. set: function (callback) {
  59085. if (this._onAfterRenderObserver) {
  59086. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59087. }
  59088. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59089. },
  59090. enumerable: true,
  59091. configurable: true
  59092. });
  59093. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59094. /**
  59095. * 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
  59096. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59097. */
  59098. get: function () {
  59099. return this._textures.data[this._currentRenderTextureInd];
  59100. },
  59101. set: function (value) {
  59102. this._forcedOutputTexture = value;
  59103. },
  59104. enumerable: true,
  59105. configurable: true
  59106. });
  59107. /**
  59108. * Gets the camera which post process is applied to.
  59109. * @returns The camera the post process is applied to.
  59110. */
  59111. PostProcess.prototype.getCamera = function () {
  59112. return this._camera;
  59113. };
  59114. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59115. /**
  59116. * Gets the texel size of the postprocess.
  59117. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59118. */
  59119. get: function () {
  59120. if (this._shareOutputWithPostProcess) {
  59121. return this._shareOutputWithPostProcess.texelSize;
  59122. }
  59123. if (this._forcedOutputTexture) {
  59124. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59125. }
  59126. return this._texelSize;
  59127. },
  59128. enumerable: true,
  59129. configurable: true
  59130. });
  59131. /**
  59132. * Gets the engine which this post process belongs to.
  59133. * @returns The engine the post process was enabled with.
  59134. */
  59135. PostProcess.prototype.getEngine = function () {
  59136. return this._engine;
  59137. };
  59138. /**
  59139. * The effect that is created when initializing the post process.
  59140. * @returns The created effect corrisponding the the postprocess.
  59141. */
  59142. PostProcess.prototype.getEffect = function () {
  59143. return this._effect;
  59144. };
  59145. /**
  59146. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59147. * @param postProcess The post process to share the output with.
  59148. * @returns This post process.
  59149. */
  59150. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59151. this._disposeTextures();
  59152. this._shareOutputWithPostProcess = postProcess;
  59153. return this;
  59154. };
  59155. /**
  59156. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59157. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59158. */
  59159. PostProcess.prototype.useOwnOutput = function () {
  59160. if (this._textures.length == 0) {
  59161. this._textures = new BABYLON.SmartArray(2);
  59162. }
  59163. this._shareOutputWithPostProcess = null;
  59164. };
  59165. /**
  59166. * Updates the effect with the current post process compile time values and recompiles the shader.
  59167. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59168. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59169. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59170. * @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
  59171. * @param onCompiled Called when the shader has been compiled.
  59172. * @param onError Called if there is an error when compiling a shader.
  59173. */
  59174. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59175. if (defines === void 0) { defines = null; }
  59176. if (uniforms === void 0) { uniforms = null; }
  59177. if (samplers === void 0) { samplers = null; }
  59178. 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);
  59179. };
  59180. /**
  59181. * The post process is reusable if it can be used multiple times within one frame.
  59182. * @returns If the post process is reusable
  59183. */
  59184. PostProcess.prototype.isReusable = function () {
  59185. return this._reusable;
  59186. };
  59187. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59188. PostProcess.prototype.markTextureDirty = function () {
  59189. this.width = -1;
  59190. };
  59191. /**
  59192. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59193. * 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.
  59194. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59195. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59196. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59197. */
  59198. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59199. var _this = this;
  59200. if (sourceTexture === void 0) { sourceTexture = null; }
  59201. camera = camera || this._camera;
  59202. var scene = camera.getScene();
  59203. var engine = scene.getEngine();
  59204. var maxSize = engine.getCaps().maxTextureSize;
  59205. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59206. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59207. // 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
  59208. var webVRCamera = camera.parent;
  59209. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59210. requiredWidth /= 2;
  59211. }
  59212. var desiredWidth = (this._options.width || requiredWidth);
  59213. var desiredHeight = this._options.height || requiredHeight;
  59214. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59215. if (this.adaptScaleToCurrentViewport) {
  59216. var currentViewport = engine.currentViewport;
  59217. if (currentViewport) {
  59218. desiredWidth *= currentViewport.width;
  59219. desiredHeight *= currentViewport.height;
  59220. }
  59221. }
  59222. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59223. if (!this._options.width) {
  59224. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59225. }
  59226. if (!this._options.height) {
  59227. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59228. }
  59229. }
  59230. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59231. if (this._textures.length > 0) {
  59232. for (var i = 0; i < this._textures.length; i++) {
  59233. this._engine._releaseTexture(this._textures.data[i]);
  59234. }
  59235. this._textures.reset();
  59236. }
  59237. this.width = desiredWidth;
  59238. this.height = desiredHeight;
  59239. var textureSize = { width: this.width, height: this.height };
  59240. var textureOptions = {
  59241. generateMipMaps: false,
  59242. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59243. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59244. samplingMode: this.renderTargetSamplingMode,
  59245. type: this._textureType
  59246. };
  59247. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59248. if (this._reusable) {
  59249. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59250. }
  59251. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59252. this.onSizeChangedObservable.notifyObservers(this);
  59253. }
  59254. this._textures.forEach(function (texture) {
  59255. if (texture.samples !== _this.samples) {
  59256. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59257. }
  59258. });
  59259. }
  59260. var target;
  59261. if (this._shareOutputWithPostProcess) {
  59262. target = this._shareOutputWithPostProcess.inputTexture;
  59263. }
  59264. else if (this._forcedOutputTexture) {
  59265. target = this._forcedOutputTexture;
  59266. this.width = this._forcedOutputTexture.width;
  59267. this.height = this._forcedOutputTexture.height;
  59268. }
  59269. else {
  59270. target = this.inputTexture;
  59271. }
  59272. // Bind the input of this post process to be used as the output of the previous post process.
  59273. if (this.enablePixelPerfectMode) {
  59274. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59275. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59276. }
  59277. else {
  59278. this._scaleRatio.copyFromFloats(1, 1);
  59279. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59280. }
  59281. this.onActivateObservable.notifyObservers(camera);
  59282. // Clear
  59283. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59284. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59285. }
  59286. if (this._reusable) {
  59287. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59288. }
  59289. };
  59290. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59291. /**
  59292. * If the post process is supported.
  59293. */
  59294. get: function () {
  59295. return this._effect.isSupported;
  59296. },
  59297. enumerable: true,
  59298. configurable: true
  59299. });
  59300. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59301. /**
  59302. * The aspect ratio of the output texture.
  59303. */
  59304. get: function () {
  59305. if (this._shareOutputWithPostProcess) {
  59306. return this._shareOutputWithPostProcess.aspectRatio;
  59307. }
  59308. if (this._forcedOutputTexture) {
  59309. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59310. }
  59311. return this.width / this.height;
  59312. },
  59313. enumerable: true,
  59314. configurable: true
  59315. });
  59316. /**
  59317. * Get a value indicating if the post-process is ready to be used
  59318. * @returns true if the post-process is ready (shader is compiled)
  59319. */
  59320. PostProcess.prototype.isReady = function () {
  59321. return this._effect && this._effect.isReady();
  59322. };
  59323. /**
  59324. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59325. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59326. */
  59327. PostProcess.prototype.apply = function () {
  59328. // Check
  59329. if (!this._effect || !this._effect.isReady())
  59330. return null;
  59331. // States
  59332. this._engine.enableEffect(this._effect);
  59333. this._engine.setState(false);
  59334. this._engine.setDepthBuffer(false);
  59335. this._engine.setDepthWrite(false);
  59336. // Alpha
  59337. this._engine.setAlphaMode(this.alphaMode);
  59338. if (this.alphaConstants) {
  59339. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59340. }
  59341. // Bind the output texture of the preivous post process as the input to this post process.
  59342. var source;
  59343. if (this._shareOutputWithPostProcess) {
  59344. source = this._shareOutputWithPostProcess.inputTexture;
  59345. }
  59346. else if (this._forcedOutputTexture) {
  59347. source = this._forcedOutputTexture;
  59348. }
  59349. else {
  59350. source = this.inputTexture;
  59351. }
  59352. this._effect._bindTexture("textureSampler", source);
  59353. // Parameters
  59354. this._effect.setVector2("scale", this._scaleRatio);
  59355. this.onApplyObservable.notifyObservers(this._effect);
  59356. return this._effect;
  59357. };
  59358. PostProcess.prototype._disposeTextures = function () {
  59359. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59360. return;
  59361. }
  59362. if (this._textures.length > 0) {
  59363. for (var i = 0; i < this._textures.length; i++) {
  59364. this._engine._releaseTexture(this._textures.data[i]);
  59365. }
  59366. }
  59367. this._textures.dispose();
  59368. };
  59369. /**
  59370. * Disposes the post process.
  59371. * @param camera The camera to dispose the post process on.
  59372. */
  59373. PostProcess.prototype.dispose = function (camera) {
  59374. camera = camera || this._camera;
  59375. this._disposeTextures();
  59376. if (this._scene) {
  59377. var index_1 = this._scene.postProcesses.indexOf(this);
  59378. if (index_1 !== -1) {
  59379. this._scene.postProcesses.splice(index_1, 1);
  59380. }
  59381. }
  59382. else {
  59383. var index_2 = this._engine.postProcesses.indexOf(this);
  59384. if (index_2 !== -1) {
  59385. this._engine.postProcesses.splice(index_2, 1);
  59386. }
  59387. }
  59388. if (!camera) {
  59389. return;
  59390. }
  59391. camera.detachPostProcess(this);
  59392. var index = camera._postProcesses.indexOf(this);
  59393. if (index === 0 && camera._postProcesses.length > 0) {
  59394. var firstPostProcess = this._camera._getFirstPostProcess();
  59395. if (firstPostProcess) {
  59396. firstPostProcess.markTextureDirty();
  59397. }
  59398. }
  59399. this.onActivateObservable.clear();
  59400. this.onAfterRenderObservable.clear();
  59401. this.onApplyObservable.clear();
  59402. this.onBeforeRenderObservable.clear();
  59403. this.onSizeChangedObservable.clear();
  59404. };
  59405. return PostProcess;
  59406. }());
  59407. BABYLON.PostProcess = PostProcess;
  59408. })(BABYLON || (BABYLON = {}));
  59409. //# sourceMappingURL=babylon.postProcess.js.map
  59410. var BABYLON;
  59411. (function (BABYLON) {
  59412. var PassPostProcess = /** @class */ (function (_super) {
  59413. __extends(PassPostProcess, _super);
  59414. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  59415. if (camera === void 0) { camera = null; }
  59416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59417. if (blockCompilation === void 0) { blockCompilation = false; }
  59418. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  59419. }
  59420. return PassPostProcess;
  59421. }(BABYLON.PostProcess));
  59422. BABYLON.PassPostProcess = PassPostProcess;
  59423. })(BABYLON || (BABYLON = {}));
  59424. //# sourceMappingURL=babylon.passPostProcess.js.map
  59425. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59426. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59427. s = arguments[i];
  59428. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59429. t[p] = s[p];
  59430. }
  59431. return t;
  59432. };
  59433. var BABYLON;
  59434. (function (BABYLON) {
  59435. /**
  59436. * Default implementation of @see IShadowGenerator.
  59437. * This is the main object responsible of generating shadows in the framework.
  59438. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59439. */
  59440. var ShadowGenerator = /** @class */ (function () {
  59441. /**
  59442. * Creates a ShadowGenerator object.
  59443. * A ShadowGenerator is the required tool to use the shadows.
  59444. * Each light casting shadows needs to use its own ShadowGenerator.
  59445. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59446. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59447. * @param light The light object generating the shadows.
  59448. * @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.
  59449. */
  59450. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59451. this._bias = 0.00005;
  59452. this._blurBoxOffset = 1;
  59453. this._blurScale = 2;
  59454. this._blurKernel = 1;
  59455. this._useKernelBlur = false;
  59456. this._filter = ShadowGenerator.FILTER_NONE;
  59457. this._darkness = 0;
  59458. this._transparencyShadow = false;
  59459. /**
  59460. * Controls the extent to which the shadows fade out at the edge of the frustum
  59461. * Used only by directionals and spots
  59462. */
  59463. this.frustumEdgeFalloff = 0;
  59464. /**
  59465. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59466. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59467. * It might on the other hand introduce peter panning.
  59468. */
  59469. this.forceBackFacesOnly = false;
  59470. this._lightDirection = BABYLON.Vector3.Zero();
  59471. this._viewMatrix = BABYLON.Matrix.Zero();
  59472. this._projectionMatrix = BABYLON.Matrix.Zero();
  59473. this._transformMatrix = BABYLON.Matrix.Zero();
  59474. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59475. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59476. this._currentFaceIndex = 0;
  59477. this._currentFaceIndexCache = 0;
  59478. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59479. this._mapSize = mapSize;
  59480. this._light = light;
  59481. this._scene = light.getScene();
  59482. light._shadowGenerator = this;
  59483. // Texture type fallback from float to int if not supported.
  59484. var caps = this._scene.getEngine().getCaps();
  59485. if (!useFullFloatFirst) {
  59486. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59487. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59488. }
  59489. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59490. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59491. }
  59492. else {
  59493. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59494. }
  59495. }
  59496. else {
  59497. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59498. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59499. }
  59500. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59501. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59502. }
  59503. else {
  59504. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59505. }
  59506. }
  59507. this._initializeGenerator();
  59508. }
  59509. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59510. /**
  59511. * Shadow generator mode None: no filtering applied.
  59512. */
  59513. get: function () {
  59514. return ShadowGenerator._FILTER_NONE;
  59515. },
  59516. enumerable: true,
  59517. configurable: true
  59518. });
  59519. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59520. /**
  59521. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59522. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59523. */
  59524. get: function () {
  59525. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59526. },
  59527. enumerable: true,
  59528. configurable: true
  59529. });
  59530. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59531. /**
  59532. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59533. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59534. */
  59535. get: function () {
  59536. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59537. },
  59538. enumerable: true,
  59539. configurable: true
  59540. });
  59541. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59542. /**
  59543. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59544. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59545. */
  59546. get: function () {
  59547. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59548. },
  59549. enumerable: true,
  59550. configurable: true
  59551. });
  59552. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59553. /**
  59554. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59555. * edge artifacts on steep falloff.
  59556. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59557. */
  59558. get: function () {
  59559. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59560. },
  59561. enumerable: true,
  59562. configurable: true
  59563. });
  59564. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59565. /**
  59566. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59567. * edge artifacts on steep falloff.
  59568. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59569. */
  59570. get: function () {
  59571. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59572. },
  59573. enumerable: true,
  59574. configurable: true
  59575. });
  59576. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59577. /**
  59578. * Gets the bias: offset applied on the depth preventing acnea.
  59579. */
  59580. get: function () {
  59581. return this._bias;
  59582. },
  59583. /**
  59584. * Sets the bias: offset applied on the depth preventing acnea.
  59585. */
  59586. set: function (bias) {
  59587. this._bias = bias;
  59588. },
  59589. enumerable: true,
  59590. configurable: true
  59591. });
  59592. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59593. /**
  59594. * Gets the blur box offset: offset applied during the blur pass.
  59595. * Only usefull if useKernelBlur = false
  59596. */
  59597. get: function () {
  59598. return this._blurBoxOffset;
  59599. },
  59600. /**
  59601. * Sets the blur box offset: offset applied during the blur pass.
  59602. * Only usefull if useKernelBlur = false
  59603. */
  59604. set: function (value) {
  59605. if (this._blurBoxOffset === value) {
  59606. return;
  59607. }
  59608. this._blurBoxOffset = value;
  59609. this._disposeBlurPostProcesses();
  59610. },
  59611. enumerable: true,
  59612. configurable: true
  59613. });
  59614. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59615. /**
  59616. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59617. * 2 means half of the size.
  59618. */
  59619. get: function () {
  59620. return this._blurScale;
  59621. },
  59622. /**
  59623. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59624. * 2 means half of the size.
  59625. */
  59626. set: function (value) {
  59627. if (this._blurScale === value) {
  59628. return;
  59629. }
  59630. this._blurScale = value;
  59631. this._disposeBlurPostProcesses();
  59632. },
  59633. enumerable: true,
  59634. configurable: true
  59635. });
  59636. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59637. /**
  59638. * Gets the blur kernel: kernel size of the blur pass.
  59639. * Only usefull if useKernelBlur = true
  59640. */
  59641. get: function () {
  59642. return this._blurKernel;
  59643. },
  59644. /**
  59645. * Sets the blur kernel: kernel size of the blur pass.
  59646. * Only usefull if useKernelBlur = true
  59647. */
  59648. set: function (value) {
  59649. if (this._blurKernel === value) {
  59650. return;
  59651. }
  59652. this._blurKernel = value;
  59653. this._disposeBlurPostProcesses();
  59654. },
  59655. enumerable: true,
  59656. configurable: true
  59657. });
  59658. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59659. /**
  59660. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59661. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59662. */
  59663. get: function () {
  59664. return this._useKernelBlur;
  59665. },
  59666. /**
  59667. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59668. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59669. */
  59670. set: function (value) {
  59671. if (this._useKernelBlur === value) {
  59672. return;
  59673. }
  59674. this._useKernelBlur = value;
  59675. this._disposeBlurPostProcesses();
  59676. },
  59677. enumerable: true,
  59678. configurable: true
  59679. });
  59680. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59681. /**
  59682. * Gets the depth scale used in ESM mode.
  59683. */
  59684. get: function () {
  59685. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59686. },
  59687. /**
  59688. * Sets the depth scale used in ESM mode.
  59689. * This can override the scale stored on the light.
  59690. */
  59691. set: function (value) {
  59692. this._depthScale = value;
  59693. },
  59694. enumerable: true,
  59695. configurable: true
  59696. });
  59697. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59698. /**
  59699. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59700. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59701. */
  59702. get: function () {
  59703. return this._filter;
  59704. },
  59705. /**
  59706. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59707. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59708. */
  59709. set: function (value) {
  59710. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59711. if (this._light.needCube()) {
  59712. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59713. this.useExponentialShadowMap = true;
  59714. return;
  59715. }
  59716. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59717. this.useCloseExponentialShadowMap = true;
  59718. return;
  59719. }
  59720. }
  59721. if (this._filter === value) {
  59722. return;
  59723. }
  59724. this._filter = value;
  59725. this._disposeBlurPostProcesses();
  59726. this._applyFilterValues();
  59727. this._light._markMeshesAsLightDirty();
  59728. },
  59729. enumerable: true,
  59730. configurable: true
  59731. });
  59732. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59733. /**
  59734. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59735. */
  59736. get: function () {
  59737. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59738. },
  59739. /**
  59740. * Sets the current filter to Poisson Sampling aka PCF.
  59741. */
  59742. set: function (value) {
  59743. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59744. return;
  59745. }
  59746. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59747. },
  59748. enumerable: true,
  59749. configurable: true
  59750. });
  59751. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59752. /**
  59753. * Gets if the current filter is set to VSM.
  59754. * DEPRECATED. Should use useExponentialShadowMap instead.
  59755. */
  59756. get: function () {
  59757. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59758. return this.useExponentialShadowMap;
  59759. },
  59760. /**
  59761. * Sets the current filter is to VSM.
  59762. * DEPRECATED. Should use useExponentialShadowMap instead.
  59763. */
  59764. set: function (value) {
  59765. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59766. this.useExponentialShadowMap = value;
  59767. },
  59768. enumerable: true,
  59769. configurable: true
  59770. });
  59771. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59772. /**
  59773. * Gets if the current filter is set to blurred VSM.
  59774. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59775. */
  59776. get: function () {
  59777. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59778. return this.useBlurExponentialShadowMap;
  59779. },
  59780. /**
  59781. * Sets the current filter is to blurred VSM.
  59782. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59783. */
  59784. set: function (value) {
  59785. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59786. this.useBlurExponentialShadowMap = value;
  59787. },
  59788. enumerable: true,
  59789. configurable: true
  59790. });
  59791. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59792. /**
  59793. * Gets if the current filter is set to ESM.
  59794. */
  59795. get: function () {
  59796. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59797. },
  59798. /**
  59799. * Sets the current filter is to ESM.
  59800. */
  59801. set: function (value) {
  59802. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59803. return;
  59804. }
  59805. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59806. },
  59807. enumerable: true,
  59808. configurable: true
  59809. });
  59810. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59811. /**
  59812. * Gets if the current filter is set to filtered ESM.
  59813. */
  59814. get: function () {
  59815. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59816. },
  59817. /**
  59818. * Gets if the current filter is set to filtered ESM.
  59819. */
  59820. set: function (value) {
  59821. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59822. return;
  59823. }
  59824. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59825. },
  59826. enumerable: true,
  59827. configurable: true
  59828. });
  59829. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59830. /**
  59831. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59832. * exponential to prevent steep falloff artifacts).
  59833. */
  59834. get: function () {
  59835. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59836. },
  59837. /**
  59838. * Sets the current filter to "close ESM" (using the inverse of the
  59839. * exponential to prevent steep falloff artifacts).
  59840. */
  59841. set: function (value) {
  59842. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59843. return;
  59844. }
  59845. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59846. },
  59847. enumerable: true,
  59848. configurable: true
  59849. });
  59850. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59851. /**
  59852. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59853. * exponential to prevent steep falloff artifacts).
  59854. */
  59855. get: function () {
  59856. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59857. },
  59858. /**
  59859. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59860. * exponential to prevent steep falloff artifacts).
  59861. */
  59862. set: function (value) {
  59863. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59864. return;
  59865. }
  59866. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59867. },
  59868. enumerable: true,
  59869. configurable: true
  59870. });
  59871. /**
  59872. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59873. * 0 means strongest and 1 would means no shadow.
  59874. * @returns the darkness.
  59875. */
  59876. ShadowGenerator.prototype.getDarkness = function () {
  59877. return this._darkness;
  59878. };
  59879. /**
  59880. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59881. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59882. * @returns the shadow generator allowing fluent coding.
  59883. */
  59884. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59885. if (darkness >= 1.0)
  59886. this._darkness = 1.0;
  59887. else if (darkness <= 0.0)
  59888. this._darkness = 0.0;
  59889. else
  59890. this._darkness = darkness;
  59891. return this;
  59892. };
  59893. /**
  59894. * Sets the ability to have transparent shadow (boolean).
  59895. * @param transparent True if transparent else False
  59896. * @returns the shadow generator allowing fluent coding
  59897. */
  59898. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59899. this._transparencyShadow = transparent;
  59900. return this;
  59901. };
  59902. /**
  59903. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59904. * @returns The render target texture if present otherwise, null
  59905. */
  59906. ShadowGenerator.prototype.getShadowMap = function () {
  59907. return this._shadowMap;
  59908. };
  59909. /**
  59910. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59911. * @returns The render target texture if the shadow map is present otherwise, null
  59912. */
  59913. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59914. if (this._shadowMap2) {
  59915. return this._shadowMap2;
  59916. }
  59917. return this._shadowMap;
  59918. };
  59919. /**
  59920. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59921. * @param mesh Mesh to add
  59922. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59923. * @returns the Shadow Generator itself
  59924. */
  59925. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59926. if (includeDescendants === void 0) { includeDescendants = true; }
  59927. if (!this._shadowMap) {
  59928. return this;
  59929. }
  59930. if (!this._shadowMap.renderList) {
  59931. this._shadowMap.renderList = [];
  59932. }
  59933. this._shadowMap.renderList.push(mesh);
  59934. if (includeDescendants) {
  59935. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59936. }
  59937. return this;
  59938. var _a;
  59939. };
  59940. /**
  59941. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59942. * @param mesh Mesh to remove
  59943. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59944. * @returns the Shadow Generator itself
  59945. */
  59946. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59947. if (includeDescendants === void 0) { includeDescendants = true; }
  59948. if (!this._shadowMap || !this._shadowMap.renderList) {
  59949. return this;
  59950. }
  59951. var index = this._shadowMap.renderList.indexOf(mesh);
  59952. if (index !== -1) {
  59953. this._shadowMap.renderList.splice(index, 1);
  59954. }
  59955. if (includeDescendants) {
  59956. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59957. var child = _a[_i];
  59958. this.removeShadowCaster(child);
  59959. }
  59960. }
  59961. return this;
  59962. };
  59963. /**
  59964. * Returns the associated light object.
  59965. * @returns the light generating the shadow
  59966. */
  59967. ShadowGenerator.prototype.getLight = function () {
  59968. return this._light;
  59969. };
  59970. ShadowGenerator.prototype._initializeGenerator = function () {
  59971. this._light._markMeshesAsLightDirty();
  59972. this._initializeShadowMap();
  59973. };
  59974. ShadowGenerator.prototype._initializeShadowMap = function () {
  59975. var _this = this;
  59976. // Render target
  59977. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59978. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59979. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59980. this._shadowMap.anisotropicFilteringLevel = 1;
  59981. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59982. this._shadowMap.renderParticles = false;
  59983. this._shadowMap.ignoreCameraViewport = true;
  59984. // Record Face Index before render.
  59985. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59986. _this._currentFaceIndex = faceIndex;
  59987. });
  59988. // Custom render function.
  59989. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59990. // Blur if required afer render.
  59991. this._shadowMap.onAfterUnbindObservable.add(function () {
  59992. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59993. return;
  59994. }
  59995. var shadowMap = _this.getShadowMapForRendering();
  59996. if (shadowMap) {
  59997. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59998. }
  59999. });
  60000. // Clear according to the chosen filter.
  60001. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60002. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60003. this._shadowMap.onClearObservable.add(function (engine) {
  60004. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60005. engine.clear(zero, true, true, true);
  60006. }
  60007. else {
  60008. engine.clear(one, true, true, true);
  60009. }
  60010. });
  60011. };
  60012. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60013. var _this = this;
  60014. var engine = this._scene.getEngine();
  60015. var targetSize = this._mapSize / this.blurScale;
  60016. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60017. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60018. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60019. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60020. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60021. }
  60022. if (this.useKernelBlur) {
  60023. 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);
  60024. this._kernelBlurXPostprocess.width = targetSize;
  60025. this._kernelBlurXPostprocess.height = targetSize;
  60026. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60027. effect.setTexture("textureSampler", _this._shadowMap);
  60028. });
  60029. 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);
  60030. this._kernelBlurXPostprocess.autoClear = false;
  60031. this._kernelBlurYPostprocess.autoClear = false;
  60032. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60033. this._kernelBlurXPostprocess.packedFloat = true;
  60034. this._kernelBlurYPostprocess.packedFloat = true;
  60035. }
  60036. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60037. }
  60038. else {
  60039. 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);
  60040. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60041. effect.setFloat2("screenSize", targetSize, targetSize);
  60042. effect.setTexture("textureSampler", _this._shadowMap);
  60043. });
  60044. this._boxBlurPostprocess.autoClear = false;
  60045. this._blurPostProcesses = [this._boxBlurPostprocess];
  60046. }
  60047. };
  60048. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60049. var index;
  60050. var engine = this._scene.getEngine();
  60051. if (depthOnlySubMeshes.length) {
  60052. engine.setColorWrite(false);
  60053. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60054. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60055. }
  60056. engine.setColorWrite(true);
  60057. }
  60058. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60059. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60060. }
  60061. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60062. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60063. }
  60064. if (this._transparencyShadow) {
  60065. for (index = 0; index < transparentSubMeshes.length; index++) {
  60066. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60067. }
  60068. }
  60069. };
  60070. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60071. var _this = this;
  60072. var mesh = subMesh.getRenderingMesh();
  60073. var scene = this._scene;
  60074. var engine = scene.getEngine();
  60075. var material = subMesh.getMaterial();
  60076. if (!material) {
  60077. return;
  60078. }
  60079. // Culling
  60080. engine.setState(material.backFaceCulling);
  60081. // Managing instances
  60082. var batch = mesh._getInstancesRenderList(subMesh._id);
  60083. if (batch.mustReturn) {
  60084. return;
  60085. }
  60086. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60087. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60088. engine.enableEffect(this._effect);
  60089. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60090. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60091. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60092. this._effect.setVector3("lightPosition", this.getLight().position);
  60093. if (scene.activeCamera) {
  60094. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60095. }
  60096. // Alpha test
  60097. if (material && material.needAlphaTesting()) {
  60098. var alphaTexture = material.getAlphaTestTexture();
  60099. if (alphaTexture) {
  60100. this._effect.setTexture("diffuseSampler", alphaTexture);
  60101. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60102. }
  60103. }
  60104. // Bones
  60105. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60106. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60107. }
  60108. if (this.forceBackFacesOnly) {
  60109. engine.setState(true, 0, false, true);
  60110. }
  60111. // Draw
  60112. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60113. if (this.forceBackFacesOnly) {
  60114. engine.setState(true, 0, false, false);
  60115. }
  60116. }
  60117. else {
  60118. // Need to reset refresh rate of the shadowMap
  60119. if (this._shadowMap) {
  60120. this._shadowMap.resetRefreshCounter();
  60121. }
  60122. }
  60123. };
  60124. ShadowGenerator.prototype._applyFilterValues = function () {
  60125. if (!this._shadowMap) {
  60126. return;
  60127. }
  60128. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60129. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60130. }
  60131. else {
  60132. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60133. }
  60134. };
  60135. /**
  60136. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60137. * @param onCompiled Callback triggered at the and of the effects compilation
  60138. * @param options Sets of optional options forcing the compilation with different modes
  60139. */
  60140. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60141. var _this = this;
  60142. var localOptions = __assign({ useInstances: false }, options);
  60143. var shadowMap = this.getShadowMap();
  60144. if (!shadowMap) {
  60145. if (onCompiled) {
  60146. onCompiled(this);
  60147. }
  60148. return;
  60149. }
  60150. var renderList = shadowMap.renderList;
  60151. if (!renderList) {
  60152. if (onCompiled) {
  60153. onCompiled(this);
  60154. }
  60155. return;
  60156. }
  60157. var subMeshes = new Array();
  60158. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60159. var mesh = renderList_1[_i];
  60160. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60161. }
  60162. if (subMeshes.length === 0) {
  60163. if (onCompiled) {
  60164. onCompiled(this);
  60165. }
  60166. return;
  60167. }
  60168. var currentIndex = 0;
  60169. var checkReady = function () {
  60170. if (!_this._scene || !_this._scene.getEngine()) {
  60171. return;
  60172. }
  60173. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60174. currentIndex++;
  60175. if (currentIndex >= subMeshes.length) {
  60176. if (onCompiled) {
  60177. onCompiled(_this);
  60178. }
  60179. return;
  60180. }
  60181. }
  60182. setTimeout(checkReady, 16);
  60183. };
  60184. checkReady();
  60185. };
  60186. /**
  60187. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60188. * @param options Sets of optional options forcing the compilation with different modes
  60189. * @returns A promise that resolves when the compilation completes
  60190. */
  60191. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60192. var _this = this;
  60193. return new Promise(function (resolve) {
  60194. _this.forceCompilation(function () {
  60195. resolve();
  60196. }, options);
  60197. });
  60198. };
  60199. /**
  60200. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60201. * @param subMesh The submesh we want to render in the shadow map
  60202. * @param useInstances Defines wether will draw in the map using instances
  60203. * @returns true if ready otherwise, false
  60204. */
  60205. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60206. var defines = [];
  60207. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60208. defines.push("#define FLOAT");
  60209. }
  60210. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60211. defines.push("#define ESM");
  60212. }
  60213. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60214. var mesh = subMesh.getMesh();
  60215. var material = subMesh.getMaterial();
  60216. // Alpha test
  60217. if (material && material.needAlphaTesting()) {
  60218. var alphaTexture = material.getAlphaTestTexture();
  60219. if (alphaTexture) {
  60220. defines.push("#define ALPHATEST");
  60221. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60222. attribs.push(BABYLON.VertexBuffer.UVKind);
  60223. defines.push("#define UV1");
  60224. }
  60225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60226. if (alphaTexture.coordinatesIndex === 1) {
  60227. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60228. defines.push("#define UV2");
  60229. }
  60230. }
  60231. }
  60232. }
  60233. // Bones
  60234. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60235. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60236. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60237. if (mesh.numBoneInfluencers > 4) {
  60238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60240. }
  60241. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60242. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60243. }
  60244. else {
  60245. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60246. }
  60247. // Instances
  60248. if (useInstances) {
  60249. defines.push("#define INSTANCES");
  60250. attribs.push("world0");
  60251. attribs.push("world1");
  60252. attribs.push("world2");
  60253. attribs.push("world3");
  60254. }
  60255. // Get correct effect
  60256. var join = defines.join("\n");
  60257. if (this._cachedDefines !== join) {
  60258. this._cachedDefines = join;
  60259. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60260. }
  60261. if (!this._effect.isReady()) {
  60262. return false;
  60263. }
  60264. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60265. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60266. this._initializeBlurRTTAndPostProcesses();
  60267. }
  60268. }
  60269. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60270. return false;
  60271. }
  60272. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60273. return false;
  60274. }
  60275. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60276. return false;
  60277. }
  60278. return true;
  60279. };
  60280. /**
  60281. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60282. * @param defines Defines of the material we want to update
  60283. * @param lightIndex Index of the light in the enabled light list of the material
  60284. */
  60285. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60286. var scene = this._scene;
  60287. var light = this._light;
  60288. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60289. return;
  60290. }
  60291. defines["SHADOW" + lightIndex] = true;
  60292. if (this.usePoissonSampling) {
  60293. defines["SHADOWPCF" + lightIndex] = true;
  60294. }
  60295. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60296. defines["SHADOWESM" + lightIndex] = true;
  60297. }
  60298. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60299. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60300. }
  60301. if (light.needCube()) {
  60302. defines["SHADOWCUBE" + lightIndex] = true;
  60303. }
  60304. };
  60305. /**
  60306. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60307. * defined in the generator but impacting the effect).
  60308. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60309. * @param effect The effect we are binfing the information for
  60310. */
  60311. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60312. var light = this._light;
  60313. var scene = this._scene;
  60314. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60315. return;
  60316. }
  60317. var camera = scene.activeCamera;
  60318. if (!camera) {
  60319. return;
  60320. }
  60321. var shadowMap = this.getShadowMap();
  60322. if (!shadowMap) {
  60323. return;
  60324. }
  60325. if (!light.needCube()) {
  60326. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60327. }
  60328. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60329. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60330. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60331. };
  60332. /**
  60333. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60334. * (eq to shadow prjection matrix * light transform matrix)
  60335. * @returns The transform matrix used to create the shadow map
  60336. */
  60337. ShadowGenerator.prototype.getTransformMatrix = function () {
  60338. var scene = this._scene;
  60339. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60340. return this._transformMatrix;
  60341. }
  60342. this._currentRenderID = scene.getRenderId();
  60343. this._currentFaceIndexCache = this._currentFaceIndex;
  60344. var lightPosition = this._light.position;
  60345. if (this._light.computeTransformedInformation()) {
  60346. lightPosition = this._light.transformedPosition;
  60347. }
  60348. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60349. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60350. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60351. }
  60352. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60353. this._cachedPosition.copyFrom(lightPosition);
  60354. this._cachedDirection.copyFrom(this._lightDirection);
  60355. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60356. var shadowMap = this.getShadowMap();
  60357. if (shadowMap) {
  60358. var renderList = shadowMap.renderList;
  60359. if (renderList) {
  60360. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60361. }
  60362. }
  60363. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60364. }
  60365. return this._transformMatrix;
  60366. };
  60367. /**
  60368. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60369. * Cube and 2D textures for instance.
  60370. */
  60371. ShadowGenerator.prototype.recreateShadowMap = function () {
  60372. var shadowMap = this._shadowMap;
  60373. if (!shadowMap) {
  60374. return;
  60375. }
  60376. // Track render list.
  60377. var renderList = shadowMap.renderList;
  60378. // Clean up existing data.
  60379. this._disposeRTTandPostProcesses();
  60380. // Reinitializes.
  60381. this._initializeGenerator();
  60382. // Reaffect the filter to ensure a correct fallback if necessary.
  60383. this.filter = this.filter;
  60384. // Reaffect the filter.
  60385. this._applyFilterValues();
  60386. // Reaffect Render List.
  60387. this._shadowMap.renderList = renderList;
  60388. };
  60389. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60390. if (this._shadowMap2) {
  60391. this._shadowMap2.dispose();
  60392. this._shadowMap2 = null;
  60393. }
  60394. if (this._boxBlurPostprocess) {
  60395. this._boxBlurPostprocess.dispose();
  60396. this._boxBlurPostprocess = null;
  60397. }
  60398. if (this._kernelBlurXPostprocess) {
  60399. this._kernelBlurXPostprocess.dispose();
  60400. this._kernelBlurXPostprocess = null;
  60401. }
  60402. if (this._kernelBlurYPostprocess) {
  60403. this._kernelBlurYPostprocess.dispose();
  60404. this._kernelBlurYPostprocess = null;
  60405. }
  60406. this._blurPostProcesses = [];
  60407. };
  60408. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60409. if (this._shadowMap) {
  60410. this._shadowMap.dispose();
  60411. this._shadowMap = null;
  60412. }
  60413. this._disposeBlurPostProcesses();
  60414. };
  60415. /**
  60416. * Disposes the ShadowGenerator.
  60417. * Returns nothing.
  60418. */
  60419. ShadowGenerator.prototype.dispose = function () {
  60420. this._disposeRTTandPostProcesses();
  60421. if (this._light) {
  60422. this._light._shadowGenerator = null;
  60423. this._light._markMeshesAsLightDirty();
  60424. }
  60425. };
  60426. /**
  60427. * Serializes the shadow generator setup to a json object.
  60428. * @returns The serialized JSON object
  60429. */
  60430. ShadowGenerator.prototype.serialize = function () {
  60431. var serializationObject = {};
  60432. var shadowMap = this.getShadowMap();
  60433. if (!shadowMap) {
  60434. return serializationObject;
  60435. }
  60436. serializationObject.lightId = this._light.id;
  60437. serializationObject.mapSize = shadowMap.getRenderSize();
  60438. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60439. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60440. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60441. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60442. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60443. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60444. serializationObject.depthScale = this.depthScale;
  60445. serializationObject.darkness = this.getDarkness();
  60446. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60447. serializationObject.blurKernel = this.blurKernel;
  60448. serializationObject.blurScale = this.blurScale;
  60449. serializationObject.useKernelBlur = this.useKernelBlur;
  60450. serializationObject.transparencyShadow = this._transparencyShadow;
  60451. serializationObject.renderList = [];
  60452. if (shadowMap.renderList) {
  60453. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60454. var mesh = shadowMap.renderList[meshIndex];
  60455. serializationObject.renderList.push(mesh.id);
  60456. }
  60457. }
  60458. return serializationObject;
  60459. };
  60460. /**
  60461. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60462. * @param parsedShadowGenerator The JSON object to parse
  60463. * @param scene The scene to create the shadow map for
  60464. * @returns The parsed shadow generator
  60465. */
  60466. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60467. //casting to point light, as light is missing the position attr and typescript complains.
  60468. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60469. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60470. var shadowMap = shadowGenerator.getShadowMap();
  60471. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60472. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60473. meshes.forEach(function (mesh) {
  60474. if (!shadowMap) {
  60475. return;
  60476. }
  60477. if (!shadowMap.renderList) {
  60478. shadowMap.renderList = [];
  60479. }
  60480. shadowMap.renderList.push(mesh);
  60481. });
  60482. }
  60483. if (parsedShadowGenerator.usePoissonSampling) {
  60484. shadowGenerator.usePoissonSampling = true;
  60485. }
  60486. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60487. shadowGenerator.useExponentialShadowMap = true;
  60488. }
  60489. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60490. shadowGenerator.useBlurExponentialShadowMap = true;
  60491. }
  60492. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60493. shadowGenerator.useCloseExponentialShadowMap = true;
  60494. }
  60495. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60496. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60497. }
  60498. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60499. shadowGenerator.useExponentialShadowMap = true;
  60500. }
  60501. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60502. shadowGenerator.useBlurExponentialShadowMap = true;
  60503. }
  60504. if (parsedShadowGenerator.depthScale) {
  60505. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60506. }
  60507. if (parsedShadowGenerator.blurScale) {
  60508. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60509. }
  60510. if (parsedShadowGenerator.blurBoxOffset) {
  60511. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60512. }
  60513. if (parsedShadowGenerator.useKernelBlur) {
  60514. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60515. }
  60516. if (parsedShadowGenerator.blurKernel) {
  60517. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60518. }
  60519. if (parsedShadowGenerator.bias !== undefined) {
  60520. shadowGenerator.bias = parsedShadowGenerator.bias;
  60521. }
  60522. if (parsedShadowGenerator.darkness) {
  60523. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60524. }
  60525. if (parsedShadowGenerator.transparencyShadow) {
  60526. shadowGenerator.setTransparencyShadow(true);
  60527. }
  60528. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60529. return shadowGenerator;
  60530. };
  60531. ShadowGenerator._FILTER_NONE = 0;
  60532. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60533. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60534. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60535. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60536. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60537. return ShadowGenerator;
  60538. }());
  60539. BABYLON.ShadowGenerator = ShadowGenerator;
  60540. })(BABYLON || (BABYLON = {}));
  60541. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60542. var BABYLON;
  60543. (function (BABYLON) {
  60544. var DefaultLoadingScreen = /** @class */ (function () {
  60545. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60546. if (_loadingText === void 0) { _loadingText = ""; }
  60547. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60548. var _this = this;
  60549. this._renderingCanvas = _renderingCanvas;
  60550. this._loadingText = _loadingText;
  60551. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60552. // Resize
  60553. this._resizeLoadingUI = function () {
  60554. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60555. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60556. if (!_this._loadingDiv) {
  60557. return;
  60558. }
  60559. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60560. _this._loadingDiv.style.left = canvasRect.left + "px";
  60561. _this._loadingDiv.style.top = canvasRect.top + "px";
  60562. _this._loadingDiv.style.width = canvasRect.width + "px";
  60563. _this._loadingDiv.style.height = canvasRect.height + "px";
  60564. };
  60565. }
  60566. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60567. if (this._loadingDiv) {
  60568. // Do not add a loading screen if there is already one
  60569. return;
  60570. }
  60571. this._loadingDiv = document.createElement("div");
  60572. this._loadingDiv.id = "babylonjsLoadingDiv";
  60573. this._loadingDiv.style.opacity = "0";
  60574. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60575. this._loadingDiv.style.pointerEvents = "none";
  60576. // Loading text
  60577. this._loadingTextDiv = document.createElement("div");
  60578. this._loadingTextDiv.style.position = "absolute";
  60579. this._loadingTextDiv.style.left = "0";
  60580. this._loadingTextDiv.style.top = "50%";
  60581. this._loadingTextDiv.style.marginTop = "80px";
  60582. this._loadingTextDiv.style.width = "100%";
  60583. this._loadingTextDiv.style.height = "20px";
  60584. this._loadingTextDiv.style.fontFamily = "Arial";
  60585. this._loadingTextDiv.style.fontSize = "14px";
  60586. this._loadingTextDiv.style.color = "white";
  60587. this._loadingTextDiv.style.textAlign = "center";
  60588. this._loadingTextDiv.innerHTML = "Loading";
  60589. this._loadingDiv.appendChild(this._loadingTextDiv);
  60590. //set the predefined text
  60591. this._loadingTextDiv.innerHTML = this._loadingText;
  60592. // Generating keyframes
  60593. var style = document.createElement('style');
  60594. style.type = 'text/css';
  60595. 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 }";
  60596. style.innerHTML = keyFrames;
  60597. document.getElementsByTagName('head')[0].appendChild(style);
  60598. // Loading img
  60599. var imgBack = new Image();
  60600. 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";
  60601. imgBack.style.position = "absolute";
  60602. imgBack.style.left = "50%";
  60603. imgBack.style.top = "50%";
  60604. imgBack.style.marginLeft = "-60px";
  60605. imgBack.style.marginTop = "-60px";
  60606. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60607. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60608. imgBack.style.transformOrigin = "50% 50%";
  60609. imgBack.style.webkitTransformOrigin = "50% 50%";
  60610. this._loadingDiv.appendChild(imgBack);
  60611. this._resizeLoadingUI();
  60612. window.addEventListener("resize", this._resizeLoadingUI);
  60613. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60614. document.body.appendChild(this._loadingDiv);
  60615. this._loadingDiv.style.opacity = "1";
  60616. };
  60617. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60618. var _this = this;
  60619. if (!this._loadingDiv) {
  60620. return;
  60621. }
  60622. var onTransitionEnd = function () {
  60623. if (!_this._loadingDiv) {
  60624. return;
  60625. }
  60626. document.body.removeChild(_this._loadingDiv);
  60627. window.removeEventListener("resize", _this._resizeLoadingUI);
  60628. _this._loadingDiv = null;
  60629. };
  60630. this._loadingDiv.style.opacity = "0";
  60631. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60632. };
  60633. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60634. set: function (text) {
  60635. this._loadingText = text;
  60636. if (this._loadingTextDiv) {
  60637. this._loadingTextDiv.innerHTML = this._loadingText;
  60638. }
  60639. },
  60640. enumerable: true,
  60641. configurable: true
  60642. });
  60643. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60644. get: function () {
  60645. return this._loadingDivBackgroundColor;
  60646. },
  60647. set: function (color) {
  60648. this._loadingDivBackgroundColor = color;
  60649. if (!this._loadingDiv) {
  60650. return;
  60651. }
  60652. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60653. },
  60654. enumerable: true,
  60655. configurable: true
  60656. });
  60657. return DefaultLoadingScreen;
  60658. }());
  60659. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60660. })(BABYLON || (BABYLON = {}));
  60661. //# sourceMappingURL=babylon.loadingScreen.js.map
  60662. var BABYLON;
  60663. (function (BABYLON) {
  60664. var SceneLoaderProgressEvent = /** @class */ (function () {
  60665. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60666. this.lengthComputable = lengthComputable;
  60667. this.loaded = loaded;
  60668. this.total = total;
  60669. }
  60670. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60671. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60672. };
  60673. return SceneLoaderProgressEvent;
  60674. }());
  60675. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60676. var SceneLoader = /** @class */ (function () {
  60677. function SceneLoader() {
  60678. }
  60679. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60680. get: function () {
  60681. return 0;
  60682. },
  60683. enumerable: true,
  60684. configurable: true
  60685. });
  60686. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60687. get: function () {
  60688. return 1;
  60689. },
  60690. enumerable: true,
  60691. configurable: true
  60692. });
  60693. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60694. get: function () {
  60695. return 2;
  60696. },
  60697. enumerable: true,
  60698. configurable: true
  60699. });
  60700. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60701. get: function () {
  60702. return 3;
  60703. },
  60704. enumerable: true,
  60705. configurable: true
  60706. });
  60707. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60708. get: function () {
  60709. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60710. },
  60711. set: function (value) {
  60712. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60713. },
  60714. enumerable: true,
  60715. configurable: true
  60716. });
  60717. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60718. get: function () {
  60719. return SceneLoader._ShowLoadingScreen;
  60720. },
  60721. set: function (value) {
  60722. SceneLoader._ShowLoadingScreen = value;
  60723. },
  60724. enumerable: true,
  60725. configurable: true
  60726. });
  60727. Object.defineProperty(SceneLoader, "loggingLevel", {
  60728. get: function () {
  60729. return SceneLoader._loggingLevel;
  60730. },
  60731. set: function (value) {
  60732. SceneLoader._loggingLevel = value;
  60733. },
  60734. enumerable: true,
  60735. configurable: true
  60736. });
  60737. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60738. get: function () {
  60739. return SceneLoader._CleanBoneMatrixWeights;
  60740. },
  60741. set: function (value) {
  60742. SceneLoader._CleanBoneMatrixWeights = value;
  60743. },
  60744. enumerable: true,
  60745. configurable: true
  60746. });
  60747. SceneLoader._getDefaultPlugin = function () {
  60748. return SceneLoader._registeredPlugins[".babylon"];
  60749. };
  60750. SceneLoader._getPluginForExtension = function (extension) {
  60751. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60752. if (registeredPlugin) {
  60753. return registeredPlugin;
  60754. }
  60755. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60756. return SceneLoader._getDefaultPlugin();
  60757. };
  60758. SceneLoader._getPluginForDirectLoad = function (data) {
  60759. for (var extension in SceneLoader._registeredPlugins) {
  60760. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60761. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60762. return SceneLoader._registeredPlugins[extension];
  60763. }
  60764. }
  60765. return SceneLoader._getDefaultPlugin();
  60766. };
  60767. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60768. if (sceneFilename.name) {
  60769. sceneFilename = sceneFilename.name;
  60770. }
  60771. var queryStringPosition = sceneFilename.indexOf("?");
  60772. if (queryStringPosition !== -1) {
  60773. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60774. }
  60775. var dotPosition = sceneFilename.lastIndexOf(".");
  60776. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60777. return SceneLoader._getPluginForExtension(extension);
  60778. };
  60779. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60780. SceneLoader._getDirectLoad = function (sceneFilename) {
  60781. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60782. return sceneFilename.substr(5);
  60783. }
  60784. return null;
  60785. };
  60786. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60787. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60788. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60789. var plugin;
  60790. if (registeredPlugin.plugin.createPlugin) {
  60791. plugin = registeredPlugin.plugin.createPlugin();
  60792. }
  60793. else {
  60794. plugin = registeredPlugin.plugin;
  60795. }
  60796. var useArrayBuffer = registeredPlugin.isBinary;
  60797. var database;
  60798. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60799. var dataCallback = function (data, responseURL) {
  60800. if (scene.isDisposed) {
  60801. onError("Scene has been disposed");
  60802. return;
  60803. }
  60804. scene.database = database;
  60805. onSuccess(plugin, data, responseURL);
  60806. };
  60807. var request = null;
  60808. var pluginDisposed = false;
  60809. var onDisposeObservable = plugin.onDisposeObservable;
  60810. if (onDisposeObservable) {
  60811. onDisposeObservable.add(function () {
  60812. pluginDisposed = true;
  60813. if (request) {
  60814. request.abort();
  60815. request = null;
  60816. }
  60817. onDispose();
  60818. });
  60819. }
  60820. var manifestChecked = function () {
  60821. if (pluginDisposed) {
  60822. return;
  60823. }
  60824. var url = rootUrl + sceneFilename;
  60825. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60826. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60827. } : undefined, database, useArrayBuffer, function (request, exception) {
  60828. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60829. });
  60830. };
  60831. if (directLoad) {
  60832. dataCallback(directLoad);
  60833. return plugin;
  60834. }
  60835. if (rootUrl.indexOf("file:") === -1) {
  60836. if (scene.getEngine().enableOfflineSupport) {
  60837. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60838. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60839. }
  60840. else {
  60841. manifestChecked();
  60842. }
  60843. }
  60844. else {
  60845. var fileOrString = sceneFilename;
  60846. if (fileOrString.name) {
  60847. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60848. }
  60849. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60850. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60851. }
  60852. else {
  60853. onError("Unable to find file named " + sceneFilename);
  60854. }
  60855. }
  60856. return plugin;
  60857. };
  60858. // Public functions
  60859. SceneLoader.GetPluginForExtension = function (extension) {
  60860. return SceneLoader._getPluginForExtension(extension).plugin;
  60861. };
  60862. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60863. return !!SceneLoader._registeredPlugins[extension];
  60864. };
  60865. SceneLoader.RegisterPlugin = function (plugin) {
  60866. if (typeof plugin.extensions === "string") {
  60867. var extension = plugin.extensions;
  60868. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60869. plugin: plugin,
  60870. isBinary: false
  60871. };
  60872. }
  60873. else {
  60874. var extensions = plugin.extensions;
  60875. Object.keys(extensions).forEach(function (extension) {
  60876. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60877. plugin: plugin,
  60878. isBinary: extensions[extension].isBinary
  60879. };
  60880. });
  60881. }
  60882. };
  60883. /**
  60884. * Import meshes into a scene
  60885. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60886. * @param rootUrl a string that defines the root url for scene and resources
  60887. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60888. * @param scene the instance of BABYLON.Scene to append to
  60889. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60890. * @param onProgress a callback with a progress event for each file being loaded
  60891. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60892. * @param pluginExtension the extension used to determine the plugin
  60893. * @returns The loaded plugin
  60894. */
  60895. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60896. if (onSuccess === void 0) { onSuccess = null; }
  60897. if (onProgress === void 0) { onProgress = null; }
  60898. if (onError === void 0) { onError = null; }
  60899. if (pluginExtension === void 0) { pluginExtension = null; }
  60900. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60901. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60902. return null;
  60903. }
  60904. var loadingToken = {};
  60905. scene._addPendingData(loadingToken);
  60906. var disposeHandler = function () {
  60907. scene._removePendingData(loadingToken);
  60908. };
  60909. var errorHandler = function (message, exception) {
  60910. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60911. if (onError) {
  60912. onError(scene, errorMessage, exception);
  60913. }
  60914. else {
  60915. BABYLON.Tools.Error(errorMessage);
  60916. // should the exception be thrown?
  60917. }
  60918. disposeHandler();
  60919. };
  60920. var progressHandler = onProgress ? function (event) {
  60921. try {
  60922. onProgress(event);
  60923. }
  60924. catch (e) {
  60925. errorHandler("Error in onProgress callback", e);
  60926. }
  60927. } : undefined;
  60928. var successHandler = function (meshes, particleSystems, skeletons) {
  60929. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60930. if (onSuccess) {
  60931. try {
  60932. onSuccess(meshes, particleSystems, skeletons);
  60933. }
  60934. catch (e) {
  60935. errorHandler("Error in onSuccess callback", e);
  60936. }
  60937. }
  60938. scene._removePendingData(loadingToken);
  60939. };
  60940. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60941. if (plugin.rewriteRootURL) {
  60942. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60943. }
  60944. if (sceneFilename === "") {
  60945. if (sceneFilename === "") {
  60946. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60947. }
  60948. }
  60949. if (plugin.importMesh) {
  60950. var syncedPlugin = plugin;
  60951. var meshes = new Array();
  60952. var particleSystems = new Array();
  60953. var skeletons = new Array();
  60954. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60955. return;
  60956. }
  60957. scene.loadingPluginName = plugin.name;
  60958. successHandler(meshes, particleSystems, skeletons);
  60959. }
  60960. else {
  60961. var asyncedPlugin = plugin;
  60962. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60963. scene.loadingPluginName = plugin.name;
  60964. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60965. }).catch(function (error) {
  60966. errorHandler(error.message, error);
  60967. });
  60968. }
  60969. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60970. };
  60971. /**
  60972. * Import meshes into a scene
  60973. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60974. * @param rootUrl a string that defines the root url for scene and resources
  60975. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60976. * @param scene the instance of BABYLON.Scene to append to
  60977. * @param onProgress a callback with a progress event for each file being loaded
  60978. * @param pluginExtension the extension used to determine the plugin
  60979. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60980. */
  60981. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60982. if (onProgress === void 0) { onProgress = null; }
  60983. if (pluginExtension === void 0) { pluginExtension = null; }
  60984. return new Promise(function (resolve, reject) {
  60985. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60986. resolve({
  60987. meshes: meshes,
  60988. particleSystems: particleSystems,
  60989. skeletons: skeletons
  60990. });
  60991. }, onProgress, function (scene, message, exception) {
  60992. reject(exception || new Error(message));
  60993. });
  60994. });
  60995. };
  60996. /**
  60997. * Load a scene
  60998. * @param rootUrl a string that defines the root url for scene and resources
  60999. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61000. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61001. * @param onSuccess a callback with the scene when import succeeds
  61002. * @param onProgress a callback with a progress event for each file being loaded
  61003. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61004. * @param pluginExtension the extension used to determine the plugin
  61005. * @returns The loaded plugin
  61006. */
  61007. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61008. if (onSuccess === void 0) { onSuccess = null; }
  61009. if (onProgress === void 0) { onProgress = null; }
  61010. if (onError === void 0) { onError = null; }
  61011. if (pluginExtension === void 0) { pluginExtension = null; }
  61012. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61013. };
  61014. /**
  61015. * Load a scene
  61016. * @param rootUrl a string that defines the root url for scene and resources
  61017. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61018. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61019. * @param onProgress a callback with a progress event for each file being loaded
  61020. * @param pluginExtension the extension used to determine the plugin
  61021. * @returns The loaded scene
  61022. */
  61023. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61024. if (onProgress === void 0) { onProgress = null; }
  61025. if (pluginExtension === void 0) { pluginExtension = null; }
  61026. return new Promise(function (resolve, reject) {
  61027. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61028. resolve(scene);
  61029. }, onProgress, function (scene, message, exception) {
  61030. reject(exception || new Error(message));
  61031. }, pluginExtension);
  61032. });
  61033. };
  61034. /**
  61035. * Append a scene
  61036. * @param rootUrl a string that defines the root url for scene and resources
  61037. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61038. * @param scene is the instance of BABYLON.Scene to append to
  61039. * @param onSuccess a callback with the scene when import succeeds
  61040. * @param onProgress a callback with a progress event for each file being loaded
  61041. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61042. * @param pluginExtension the extension used to determine the plugin
  61043. * @returns The loaded plugin
  61044. */
  61045. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61046. if (onSuccess === void 0) { onSuccess = null; }
  61047. if (onProgress === void 0) { onProgress = null; }
  61048. if (onError === void 0) { onError = null; }
  61049. if (pluginExtension === void 0) { pluginExtension = null; }
  61050. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61051. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61052. return null;
  61053. }
  61054. if (SceneLoader.ShowLoadingScreen) {
  61055. scene.getEngine().displayLoadingUI();
  61056. }
  61057. var loadingToken = {};
  61058. scene._addPendingData(loadingToken);
  61059. var disposeHandler = function () {
  61060. scene._removePendingData(loadingToken);
  61061. scene.getEngine().hideLoadingUI();
  61062. };
  61063. var errorHandler = function (message, exception) {
  61064. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61065. if (onError) {
  61066. onError(scene, errorMessage, exception);
  61067. }
  61068. else {
  61069. BABYLON.Tools.Error(errorMessage);
  61070. // should the exception be thrown?
  61071. }
  61072. disposeHandler();
  61073. };
  61074. var progressHandler = onProgress ? function (event) {
  61075. try {
  61076. onProgress(event);
  61077. }
  61078. catch (e) {
  61079. errorHandler("Error in onProgress callback", e);
  61080. }
  61081. } : undefined;
  61082. var successHandler = function () {
  61083. if (onSuccess) {
  61084. try {
  61085. onSuccess(scene);
  61086. }
  61087. catch (e) {
  61088. errorHandler("Error in onSuccess callback", e);
  61089. }
  61090. }
  61091. scene._removePendingData(loadingToken);
  61092. };
  61093. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61094. if (sceneFilename === "") {
  61095. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61096. }
  61097. if (plugin.load) {
  61098. var syncedPlugin = plugin;
  61099. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61100. return;
  61101. }
  61102. scene.loadingPluginName = plugin.name;
  61103. successHandler();
  61104. }
  61105. else {
  61106. var asyncedPlugin = plugin;
  61107. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61108. scene.loadingPluginName = plugin.name;
  61109. successHandler();
  61110. }).catch(function (error) {
  61111. errorHandler(error.message, error);
  61112. });
  61113. }
  61114. if (SceneLoader.ShowLoadingScreen) {
  61115. scene.executeWhenReady(function () {
  61116. scene.getEngine().hideLoadingUI();
  61117. });
  61118. }
  61119. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61120. };
  61121. /**
  61122. * Append a scene
  61123. * @param rootUrl a string that defines the root url for scene and resources
  61124. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61125. * @param scene is the instance of BABYLON.Scene to append to
  61126. * @param onProgress a callback with a progress event for each file being loaded
  61127. * @param pluginExtension the extension used to determine the plugin
  61128. * @returns The given scene
  61129. */
  61130. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61131. if (onProgress === void 0) { onProgress = null; }
  61132. if (pluginExtension === void 0) { pluginExtension = null; }
  61133. return new Promise(function (resolve, reject) {
  61134. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61135. resolve(scene);
  61136. }, onProgress, function (scene, message, exception) {
  61137. reject(exception || new Error(message));
  61138. }, pluginExtension);
  61139. });
  61140. };
  61141. /**
  61142. * Load a scene into an asset container
  61143. * @param rootUrl a string that defines the root url for scene and resources
  61144. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61145. * @param scene is the instance of BABYLON.Scene to append to
  61146. * @param onSuccess a callback with the scene when import succeeds
  61147. * @param onProgress a callback with a progress event for each file being loaded
  61148. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61149. * @param pluginExtension the extension used to determine the plugin
  61150. * @returns The loaded plugin
  61151. */
  61152. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61153. if (onSuccess === void 0) { onSuccess = null; }
  61154. if (onProgress === void 0) { onProgress = null; }
  61155. if (onError === void 0) { onError = null; }
  61156. if (pluginExtension === void 0) { pluginExtension = null; }
  61157. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61158. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61159. return null;
  61160. }
  61161. var loadingToken = {};
  61162. scene._addPendingData(loadingToken);
  61163. var disposeHandler = function () {
  61164. scene._removePendingData(loadingToken);
  61165. };
  61166. var errorHandler = function (message, exception) {
  61167. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61168. if (onError) {
  61169. onError(scene, errorMessage, exception);
  61170. }
  61171. else {
  61172. BABYLON.Tools.Error(errorMessage);
  61173. // should the exception be thrown?
  61174. }
  61175. disposeHandler();
  61176. };
  61177. var progressHandler = onProgress ? function (event) {
  61178. try {
  61179. onProgress(event);
  61180. }
  61181. catch (e) {
  61182. errorHandler("Error in onProgress callback", e);
  61183. }
  61184. } : undefined;
  61185. var successHandler = function (assets) {
  61186. if (onSuccess) {
  61187. try {
  61188. onSuccess(assets);
  61189. }
  61190. catch (e) {
  61191. errorHandler("Error in onSuccess callback", e);
  61192. }
  61193. }
  61194. scene._removePendingData(loadingToken);
  61195. };
  61196. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61197. if (plugin.loadAssetContainer) {
  61198. var syncedPlugin = plugin;
  61199. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61200. if (!assetContainer) {
  61201. return;
  61202. }
  61203. scene.loadingPluginName = plugin.name;
  61204. successHandler(assetContainer);
  61205. }
  61206. else if (plugin.loadAssetContainerAsync) {
  61207. var asyncedPlugin = plugin;
  61208. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61209. scene.loadingPluginName = plugin.name;
  61210. successHandler(assetContainer);
  61211. }).catch(function (error) {
  61212. errorHandler(error.message, error);
  61213. });
  61214. }
  61215. else {
  61216. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61217. }
  61218. if (SceneLoader.ShowLoadingScreen) {
  61219. scene.executeWhenReady(function () {
  61220. scene.getEngine().hideLoadingUI();
  61221. });
  61222. }
  61223. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61224. };
  61225. /**
  61226. * Load a scene into an asset container
  61227. * @param rootUrl a string that defines the root url for scene and resources
  61228. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61229. * @param scene is the instance of BABYLON.Scene to append to
  61230. * @param onProgress a callback with a progress event for each file being loaded
  61231. * @param pluginExtension the extension used to determine the plugin
  61232. * @returns The loaded asset container
  61233. */
  61234. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61235. if (onProgress === void 0) { onProgress = null; }
  61236. if (pluginExtension === void 0) { pluginExtension = null; }
  61237. return new Promise(function (resolve, reject) {
  61238. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61239. resolve(assetContainer);
  61240. }, onProgress, function (scene, message, exception) {
  61241. reject(exception || new Error(message));
  61242. }, pluginExtension);
  61243. });
  61244. };
  61245. // Flags
  61246. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61247. SceneLoader._ShowLoadingScreen = true;
  61248. SceneLoader._CleanBoneMatrixWeights = false;
  61249. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61250. // Members
  61251. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61252. SceneLoader._registeredPlugins = {};
  61253. return SceneLoader;
  61254. }());
  61255. BABYLON.SceneLoader = SceneLoader;
  61256. ;
  61257. })(BABYLON || (BABYLON = {}));
  61258. //# sourceMappingURL=babylon.sceneLoader.js.map
  61259. var BABYLON;
  61260. (function (BABYLON) {
  61261. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61262. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61263. var parsedMaterial = parsedData.materials[index];
  61264. if (parsedMaterial.id === id) {
  61265. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61266. }
  61267. }
  61268. return null;
  61269. };
  61270. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61271. for (var i in names) {
  61272. if (mesh.name === names[i]) {
  61273. hierarchyIds.push(mesh.id);
  61274. return true;
  61275. }
  61276. }
  61277. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61278. hierarchyIds.push(mesh.id);
  61279. return true;
  61280. }
  61281. return false;
  61282. };
  61283. var logOperation = function (operation, producer) {
  61284. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61285. };
  61286. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61287. if (addToScene === void 0) { addToScene = false; }
  61288. var container = new BABYLON.AssetContainer(scene);
  61289. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61290. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61291. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61292. // and avoid problems with multiple concurrent .babylon loads.
  61293. var log = "importScene has failed JSON parse";
  61294. try {
  61295. var parsedData = JSON.parse(data);
  61296. log = "";
  61297. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61298. var index;
  61299. var cache;
  61300. // Lights
  61301. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61302. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61303. var parsedLight = parsedData.lights[index];
  61304. var light = BABYLON.Light.Parse(parsedLight, scene);
  61305. if (light) {
  61306. container.lights.push(light);
  61307. log += (index === 0 ? "\n\tLights:" : "");
  61308. log += "\n\t\t" + light.toString(fullDetails);
  61309. }
  61310. }
  61311. }
  61312. // Animations
  61313. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61314. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61315. var parsedAnimation = parsedData.animations[index];
  61316. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61317. scene.animations.push(animation);
  61318. container.animations.push(animation);
  61319. log += (index === 0 ? "\n\tAnimations:" : "");
  61320. log += "\n\t\t" + animation.toString(fullDetails);
  61321. }
  61322. }
  61323. // Materials
  61324. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61325. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61326. var parsedMaterial = parsedData.materials[index];
  61327. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61328. container.materials.push(mat);
  61329. log += (index === 0 ? "\n\tMaterials:" : "");
  61330. log += "\n\t\t" + mat.toString(fullDetails);
  61331. }
  61332. }
  61333. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61334. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61335. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61336. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61337. container.multiMaterials.push(mmat);
  61338. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61339. log += "\n\t\t" + mmat.toString(fullDetails);
  61340. }
  61341. }
  61342. // Morph targets
  61343. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61344. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61345. var managerData = _a[_i];
  61346. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61347. }
  61348. }
  61349. // Skeletons
  61350. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61351. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61352. var parsedSkeleton = parsedData.skeletons[index];
  61353. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61354. container.skeletons.push(skeleton);
  61355. log += (index === 0 ? "\n\tSkeletons:" : "");
  61356. log += "\n\t\t" + skeleton.toString(fullDetails);
  61357. }
  61358. }
  61359. // Geometries
  61360. var geometries = parsedData.geometries;
  61361. if (geometries !== undefined && geometries !== null) {
  61362. var addedGeometry = new Array();
  61363. // Boxes
  61364. var boxes = geometries.boxes;
  61365. if (boxes !== undefined && boxes !== null) {
  61366. for (index = 0, cache = boxes.length; index < cache; index++) {
  61367. var parsedBox = boxes[index];
  61368. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61369. }
  61370. }
  61371. // Spheres
  61372. var spheres = geometries.spheres;
  61373. if (spheres !== undefined && spheres !== null) {
  61374. for (index = 0, cache = spheres.length; index < cache; index++) {
  61375. var parsedSphere = spheres[index];
  61376. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61377. }
  61378. }
  61379. // Cylinders
  61380. var cylinders = geometries.cylinders;
  61381. if (cylinders !== undefined && cylinders !== null) {
  61382. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61383. var parsedCylinder = cylinders[index];
  61384. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61385. }
  61386. }
  61387. // Toruses
  61388. var toruses = geometries.toruses;
  61389. if (toruses !== undefined && toruses !== null) {
  61390. for (index = 0, cache = toruses.length; index < cache; index++) {
  61391. var parsedTorus = toruses[index];
  61392. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61393. }
  61394. }
  61395. // Grounds
  61396. var grounds = geometries.grounds;
  61397. if (grounds !== undefined && grounds !== null) {
  61398. for (index = 0, cache = grounds.length; index < cache; index++) {
  61399. var parsedGround = grounds[index];
  61400. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61401. }
  61402. }
  61403. // Planes
  61404. var planes = geometries.planes;
  61405. if (planes !== undefined && planes !== null) {
  61406. for (index = 0, cache = planes.length; index < cache; index++) {
  61407. var parsedPlane = planes[index];
  61408. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61409. }
  61410. }
  61411. // TorusKnots
  61412. var torusKnots = geometries.torusKnots;
  61413. if (torusKnots !== undefined && torusKnots !== null) {
  61414. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61415. var parsedTorusKnot = torusKnots[index];
  61416. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61417. }
  61418. }
  61419. // VertexData
  61420. var vertexData = geometries.vertexData;
  61421. if (vertexData !== undefined && vertexData !== null) {
  61422. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61423. var parsedVertexData = vertexData[index];
  61424. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61425. }
  61426. }
  61427. addedGeometry.forEach(function (g) {
  61428. if (g) {
  61429. container.geometries.push(g);
  61430. }
  61431. });
  61432. }
  61433. // Transform nodes
  61434. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61435. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61436. var parsedTransformNode = parsedData.transformNodes[index];
  61437. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61438. container.transformNodes.push(node);
  61439. }
  61440. }
  61441. // Meshes
  61442. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61443. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61444. var parsedMesh = parsedData.meshes[index];
  61445. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61446. container.meshes.push(mesh);
  61447. log += (index === 0 ? "\n\tMeshes:" : "");
  61448. log += "\n\t\t" + mesh.toString(fullDetails);
  61449. }
  61450. }
  61451. // Cameras
  61452. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61453. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61454. var parsedCamera = parsedData.cameras[index];
  61455. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61456. container.cameras.push(camera);
  61457. log += (index === 0 ? "\n\tCameras:" : "");
  61458. log += "\n\t\t" + camera.toString(fullDetails);
  61459. }
  61460. }
  61461. // Browsing all the graph to connect the dots
  61462. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61463. var camera = scene.cameras[index];
  61464. if (camera._waitingParentId) {
  61465. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61466. camera._waitingParentId = null;
  61467. }
  61468. }
  61469. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61470. var light_1 = scene.lights[index];
  61471. if (light_1 && light_1._waitingParentId) {
  61472. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61473. light_1._waitingParentId = null;
  61474. }
  61475. }
  61476. // Sounds
  61477. // TODO: add sound
  61478. var loadedSounds = [];
  61479. var loadedSound;
  61480. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61481. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61482. var parsedSound = parsedData.sounds[index];
  61483. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61484. if (!parsedSound.url)
  61485. parsedSound.url = parsedSound.name;
  61486. if (!loadedSounds[parsedSound.url]) {
  61487. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61488. loadedSounds[parsedSound.url] = loadedSound;
  61489. container.sounds.push(loadedSound);
  61490. }
  61491. else {
  61492. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61493. }
  61494. }
  61495. else {
  61496. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61497. }
  61498. }
  61499. }
  61500. loadedSounds = [];
  61501. // Connect parents & children and parse actions
  61502. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61503. var transformNode = scene.transformNodes[index];
  61504. if (transformNode._waitingParentId) {
  61505. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61506. transformNode._waitingParentId = null;
  61507. }
  61508. }
  61509. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61510. var mesh = scene.meshes[index];
  61511. if (mesh._waitingParentId) {
  61512. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61513. mesh._waitingParentId = null;
  61514. }
  61515. if (mesh._waitingActions) {
  61516. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61517. mesh._waitingActions = null;
  61518. }
  61519. }
  61520. // freeze world matrix application
  61521. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61522. var currentMesh = scene.meshes[index];
  61523. if (currentMesh._waitingFreezeWorldMatrix) {
  61524. currentMesh.freezeWorldMatrix();
  61525. currentMesh._waitingFreezeWorldMatrix = null;
  61526. }
  61527. else {
  61528. currentMesh.computeWorldMatrix(true);
  61529. }
  61530. }
  61531. // Particles Systems
  61532. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61533. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61534. var parsedParticleSystem = parsedData.particleSystems[index];
  61535. if (parsedParticleSystem.activeParticleCount) {
  61536. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61537. container.particleSystems.push(ps);
  61538. }
  61539. else {
  61540. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61541. container.particleSystems.push(ps);
  61542. }
  61543. }
  61544. }
  61545. // Lens flares
  61546. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61547. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61548. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61549. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61550. container.lensFlareSystems.push(lf);
  61551. }
  61552. }
  61553. // Shadows
  61554. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61555. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61556. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61557. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61558. container.shadowGenerators.push(sg);
  61559. }
  61560. }
  61561. // Lights exclusions / inclusions
  61562. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61563. var light_2 = scene.lights[index];
  61564. // Excluded check
  61565. if (light_2._excludedMeshesIds.length > 0) {
  61566. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61567. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61568. if (excludedMesh) {
  61569. light_2.excludedMeshes.push(excludedMesh);
  61570. }
  61571. }
  61572. light_2._excludedMeshesIds = [];
  61573. }
  61574. // Included check
  61575. if (light_2._includedOnlyMeshesIds.length > 0) {
  61576. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61577. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61578. if (includedOnlyMesh) {
  61579. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61580. }
  61581. }
  61582. light_2._includedOnlyMeshesIds = [];
  61583. }
  61584. }
  61585. // Actions (scene)
  61586. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61587. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61588. }
  61589. if (!addToScene) {
  61590. container.removeAllFromScene();
  61591. }
  61592. }
  61593. catch (err) {
  61594. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61595. if (onError) {
  61596. onError(msg, err);
  61597. }
  61598. else {
  61599. BABYLON.Tools.Log(msg);
  61600. throw err;
  61601. }
  61602. }
  61603. finally {
  61604. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61605. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61606. }
  61607. }
  61608. return container;
  61609. };
  61610. BABYLON.SceneLoader.RegisterPlugin({
  61611. name: "babylon.js",
  61612. extensions: ".babylon",
  61613. canDirectLoad: function (data) {
  61614. if (data.indexOf("babylon") !== -1) {
  61615. return true;
  61616. }
  61617. return false;
  61618. },
  61619. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61620. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61621. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61622. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61623. // and avoid problems with multiple concurrent .babylon loads.
  61624. var log = "importMesh has failed JSON parse";
  61625. try {
  61626. var parsedData = JSON.parse(data);
  61627. log = "";
  61628. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61629. if (!meshesNames) {
  61630. meshesNames = null;
  61631. }
  61632. else if (!Array.isArray(meshesNames)) {
  61633. meshesNames = [meshesNames];
  61634. }
  61635. var hierarchyIds = new Array();
  61636. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61637. var loadedSkeletonsIds = [];
  61638. var loadedMaterialsIds = [];
  61639. var index;
  61640. var cache;
  61641. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61642. var parsedMesh = parsedData.meshes[index];
  61643. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61644. if (meshesNames !== null) {
  61645. // Remove found mesh name from list.
  61646. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61647. }
  61648. //Geometry?
  61649. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61650. //does the file contain geometries?
  61651. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61652. //find the correct geometry and add it to the scene
  61653. var found = false;
  61654. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61655. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61656. return;
  61657. }
  61658. else {
  61659. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61660. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61661. switch (geometryType) {
  61662. case "boxes":
  61663. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61664. break;
  61665. case "spheres":
  61666. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61667. break;
  61668. case "cylinders":
  61669. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61670. break;
  61671. case "toruses":
  61672. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61673. break;
  61674. case "grounds":
  61675. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61676. break;
  61677. case "planes":
  61678. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61679. break;
  61680. case "torusKnots":
  61681. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61682. break;
  61683. case "vertexData":
  61684. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61685. break;
  61686. }
  61687. found = true;
  61688. }
  61689. });
  61690. }
  61691. });
  61692. if (found === false) {
  61693. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61694. }
  61695. }
  61696. }
  61697. // Material ?
  61698. if (parsedMesh.materialId) {
  61699. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61700. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61701. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61702. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61703. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61704. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61705. var subMatId = parsedMultiMaterial.materials[matIndex];
  61706. loadedMaterialsIds.push(subMatId);
  61707. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61708. if (mat) {
  61709. log += "\n\tMaterial " + mat.toString(fullDetails);
  61710. }
  61711. }
  61712. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61713. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61714. if (mmat) {
  61715. materialFound = true;
  61716. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61717. }
  61718. break;
  61719. }
  61720. }
  61721. }
  61722. if (materialFound === false) {
  61723. loadedMaterialsIds.push(parsedMesh.materialId);
  61724. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61725. if (!mat) {
  61726. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61727. }
  61728. else {
  61729. log += "\n\tMaterial " + mat.toString(fullDetails);
  61730. }
  61731. }
  61732. }
  61733. // Skeleton ?
  61734. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61735. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61736. if (skeletonAlreadyLoaded === false) {
  61737. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61738. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61739. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61740. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61741. skeletons.push(skeleton);
  61742. loadedSkeletonsIds.push(parsedSkeleton.id);
  61743. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61744. }
  61745. }
  61746. }
  61747. }
  61748. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61749. meshes.push(mesh);
  61750. log += "\n\tMesh " + mesh.toString(fullDetails);
  61751. }
  61752. }
  61753. // Connecting parents
  61754. var currentMesh;
  61755. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61756. currentMesh = scene.meshes[index];
  61757. if (currentMesh._waitingParentId) {
  61758. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61759. currentMesh._waitingParentId = null;
  61760. }
  61761. }
  61762. // freeze and compute world matrix application
  61763. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61764. currentMesh = scene.meshes[index];
  61765. if (currentMesh._waitingFreezeWorldMatrix) {
  61766. currentMesh.freezeWorldMatrix();
  61767. currentMesh._waitingFreezeWorldMatrix = null;
  61768. }
  61769. else {
  61770. currentMesh.computeWorldMatrix(true);
  61771. }
  61772. }
  61773. }
  61774. // Particles
  61775. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61776. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61777. var parsedParticleSystem = parsedData.particleSystems[index];
  61778. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61779. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61780. }
  61781. }
  61782. }
  61783. return true;
  61784. }
  61785. catch (err) {
  61786. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61787. if (onError) {
  61788. onError(msg, err);
  61789. }
  61790. else {
  61791. BABYLON.Tools.Log(msg);
  61792. throw err;
  61793. }
  61794. }
  61795. finally {
  61796. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61797. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61798. }
  61799. }
  61800. return false;
  61801. },
  61802. load: function (scene, data, rootUrl, onError) {
  61803. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61804. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61805. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61806. // and avoid problems with multiple concurrent .babylon loads.
  61807. var log = "importScene has failed JSON parse";
  61808. try {
  61809. var parsedData = JSON.parse(data);
  61810. log = "";
  61811. // Scene
  61812. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61813. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61814. }
  61815. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61816. scene.autoClear = parsedData.autoClear;
  61817. }
  61818. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61819. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61820. }
  61821. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61822. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61823. }
  61824. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61825. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61826. }
  61827. // Fog
  61828. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61829. scene.fogMode = parsedData.fogMode;
  61830. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61831. scene.fogStart = parsedData.fogStart;
  61832. scene.fogEnd = parsedData.fogEnd;
  61833. scene.fogDensity = parsedData.fogDensity;
  61834. log += "\tFog mode for scene: ";
  61835. switch (scene.fogMode) {
  61836. // getters not compiling, so using hardcoded
  61837. case 1:
  61838. log += "exp\n";
  61839. break;
  61840. case 2:
  61841. log += "exp2\n";
  61842. break;
  61843. case 3:
  61844. log += "linear\n";
  61845. break;
  61846. }
  61847. }
  61848. //Physics
  61849. if (parsedData.physicsEnabled) {
  61850. var physicsPlugin;
  61851. if (parsedData.physicsEngine === "cannon") {
  61852. physicsPlugin = new BABYLON.CannonJSPlugin();
  61853. }
  61854. else if (parsedData.physicsEngine === "oimo") {
  61855. physicsPlugin = new BABYLON.OimoJSPlugin();
  61856. }
  61857. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61858. //else - default engine, which is currently oimo
  61859. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61860. scene.enablePhysics(physicsGravity, physicsPlugin);
  61861. }
  61862. // Metadata
  61863. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61864. scene.metadata = parsedData.metadata;
  61865. }
  61866. //collisions, if defined. otherwise, default is true
  61867. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61868. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61869. }
  61870. scene.workerCollisions = !!parsedData.workerCollisions;
  61871. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61872. if (!container) {
  61873. return false;
  61874. }
  61875. if (parsedData.autoAnimate) {
  61876. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61877. }
  61878. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61879. scene.setActiveCameraByID(parsedData.activeCameraID);
  61880. }
  61881. // Environment texture
  61882. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61883. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61884. if (parsedData.createDefaultSkybox === true) {
  61885. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61886. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61887. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61888. }
  61889. }
  61890. // Finish
  61891. return true;
  61892. }
  61893. catch (err) {
  61894. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61895. if (onError) {
  61896. onError(msg, err);
  61897. }
  61898. else {
  61899. BABYLON.Tools.Log(msg);
  61900. throw err;
  61901. }
  61902. }
  61903. finally {
  61904. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61905. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61906. }
  61907. }
  61908. return false;
  61909. },
  61910. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61911. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61912. return container;
  61913. }
  61914. });
  61915. })(BABYLON || (BABYLON = {}));
  61916. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61917. var BABYLON;
  61918. (function (BABYLON) {
  61919. var FilesInput = /** @class */ (function () {
  61920. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61921. this.onProcessFileCallback = function () { return true; };
  61922. this._engine = engine;
  61923. this._currentScene = scene;
  61924. this._sceneLoadedCallback = sceneLoadedCallback;
  61925. this._progressCallback = progressCallback;
  61926. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61927. this._textureLoadingCallback = textureLoadingCallback;
  61928. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61929. this._onReloadCallback = onReloadCallback;
  61930. this._errorCallback = errorCallback;
  61931. }
  61932. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61933. var _this = this;
  61934. if (elementToMonitor) {
  61935. this._elementToMonitor = elementToMonitor;
  61936. this._dragEnterHandler = function (e) { _this.drag(e); };
  61937. this._dragOverHandler = function (e) { _this.drag(e); };
  61938. this._dropHandler = function (e) { _this.drop(e); };
  61939. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61940. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61941. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61942. }
  61943. };
  61944. FilesInput.prototype.dispose = function () {
  61945. if (!this._elementToMonitor) {
  61946. return;
  61947. }
  61948. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61949. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61950. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61951. };
  61952. FilesInput.prototype.renderFunction = function () {
  61953. if (this._additionalRenderLoopLogicCallback) {
  61954. this._additionalRenderLoopLogicCallback();
  61955. }
  61956. if (this._currentScene) {
  61957. if (this._textureLoadingCallback) {
  61958. var remaining = this._currentScene.getWaitingItemsCount();
  61959. if (remaining > 0) {
  61960. this._textureLoadingCallback(remaining);
  61961. }
  61962. }
  61963. this._currentScene.render();
  61964. }
  61965. };
  61966. FilesInput.prototype.drag = function (e) {
  61967. e.stopPropagation();
  61968. e.preventDefault();
  61969. };
  61970. FilesInput.prototype.drop = function (eventDrop) {
  61971. eventDrop.stopPropagation();
  61972. eventDrop.preventDefault();
  61973. this.loadFiles(eventDrop);
  61974. };
  61975. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61976. var _this = this;
  61977. var reader = folder.createReader();
  61978. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61979. reader.readEntries(function (entries) {
  61980. remaining.count += entries.length;
  61981. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61982. var entry = entries_1[_i];
  61983. if (entry.isFile) {
  61984. entry.file(function (file) {
  61985. file.correctName = relativePath + file.name;
  61986. files.push(file);
  61987. if (--remaining.count === 0) {
  61988. callback();
  61989. }
  61990. });
  61991. }
  61992. else if (entry.isDirectory) {
  61993. _this._traverseFolder(entry, files, remaining, callback);
  61994. }
  61995. }
  61996. if (--remaining.count) {
  61997. callback();
  61998. }
  61999. });
  62000. };
  62001. FilesInput.prototype._processFiles = function (files) {
  62002. for (var i = 0; i < files.length; i++) {
  62003. var name = files[i].correctName.toLowerCase();
  62004. var extension = name.split('.').pop();
  62005. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62006. continue;
  62007. }
  62008. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62009. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62010. this._sceneFileToLoad = files[i];
  62011. }
  62012. else {
  62013. FilesInput.FilesToLoad[name] = files[i];
  62014. }
  62015. }
  62016. };
  62017. FilesInput.prototype.loadFiles = function (event) {
  62018. var _this = this;
  62019. if (this._startingProcessingFilesCallback)
  62020. this._startingProcessingFilesCallback();
  62021. // Handling data transfer via drag'n'drop
  62022. if (event && event.dataTransfer && event.dataTransfer.files) {
  62023. this._filesToLoad = event.dataTransfer.files;
  62024. }
  62025. // Handling files from input files
  62026. if (event && event.target && event.target.files) {
  62027. this._filesToLoad = event.target.files;
  62028. }
  62029. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62030. var files_1 = new Array();
  62031. var folders = [];
  62032. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62033. for (var i = 0; i < this._filesToLoad.length; i++) {
  62034. var fileToLoad = this._filesToLoad[i];
  62035. var name_1 = fileToLoad.name.toLowerCase();
  62036. var entry = void 0;
  62037. fileToLoad.correctName = name_1;
  62038. if (items) {
  62039. var item = items[i];
  62040. if (item.getAsEntry) {
  62041. entry = item.getAsEntry();
  62042. }
  62043. else if (item.webkitGetAsEntry) {
  62044. entry = item.webkitGetAsEntry();
  62045. }
  62046. }
  62047. if (!entry) {
  62048. files_1.push(fileToLoad);
  62049. }
  62050. else {
  62051. if (entry.isDirectory) {
  62052. folders.push(entry);
  62053. }
  62054. else {
  62055. files_1.push(fileToLoad);
  62056. }
  62057. }
  62058. }
  62059. if (folders.length === 0) {
  62060. this._processFiles(files_1);
  62061. this._processReload();
  62062. }
  62063. else {
  62064. var remaining = { count: folders.length };
  62065. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62066. var folder = folders_1[_i];
  62067. this._traverseFolder(folder, files_1, remaining, function () {
  62068. _this._processFiles(files_1);
  62069. if (remaining.count === 0) {
  62070. _this._processReload();
  62071. }
  62072. });
  62073. }
  62074. }
  62075. }
  62076. };
  62077. FilesInput.prototype._processReload = function () {
  62078. if (this._onReloadCallback) {
  62079. this._onReloadCallback(this._sceneFileToLoad);
  62080. }
  62081. else {
  62082. this.reload();
  62083. }
  62084. };
  62085. FilesInput.prototype.reload = function () {
  62086. var _this = this;
  62087. // If a scene file has been provided
  62088. if (this._sceneFileToLoad) {
  62089. if (this._currentScene) {
  62090. if (BABYLON.Tools.errorsCount > 0) {
  62091. BABYLON.Tools.ClearLogCache();
  62092. }
  62093. this._engine.stopRenderLoop();
  62094. this._currentScene.dispose();
  62095. }
  62096. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62097. if (_this._progressCallback) {
  62098. _this._progressCallback(progress);
  62099. }
  62100. }).then(function (scene) {
  62101. _this._currentScene = scene;
  62102. if (_this._sceneLoadedCallback) {
  62103. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62104. }
  62105. // Wait for textures and shaders to be ready
  62106. _this._currentScene.executeWhenReady(function () {
  62107. _this._engine.runRenderLoop(function () {
  62108. _this.renderFunction();
  62109. });
  62110. });
  62111. }).catch(function (error) {
  62112. if (_this._errorCallback) {
  62113. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62114. }
  62115. });
  62116. }
  62117. else {
  62118. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62119. }
  62120. };
  62121. FilesInput.FilesToLoad = {};
  62122. return FilesInput;
  62123. }());
  62124. BABYLON.FilesInput = FilesInput;
  62125. })(BABYLON || (BABYLON = {}));
  62126. //# sourceMappingURL=babylon.filesInput.js.map
  62127. var BABYLON;
  62128. (function (BABYLON) {
  62129. /**
  62130. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62131. * The underlying implementation relies on an associative array to ensure the best performances.
  62132. * The value can be anything including 'null' but except 'undefined'
  62133. */
  62134. var StringDictionary = /** @class */ (function () {
  62135. function StringDictionary() {
  62136. this._count = 0;
  62137. this._data = {};
  62138. }
  62139. /**
  62140. * This will clear this dictionary and copy the content from the 'source' one.
  62141. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62142. * @param source the dictionary to take the content from and copy to this dictionary
  62143. */
  62144. StringDictionary.prototype.copyFrom = function (source) {
  62145. var _this = this;
  62146. this.clear();
  62147. source.forEach(function (t, v) { return _this.add(t, v); });
  62148. };
  62149. /**
  62150. * Get a value based from its key
  62151. * @param key the given key to get the matching value from
  62152. * @return the value if found, otherwise undefined is returned
  62153. */
  62154. StringDictionary.prototype.get = function (key) {
  62155. var val = this._data[key];
  62156. if (val !== undefined) {
  62157. return val;
  62158. }
  62159. return undefined;
  62160. };
  62161. /**
  62162. * Get a value from its key or add it if it doesn't exist.
  62163. * This method will ensure you that a given key/data will be present in the dictionary.
  62164. * @param key the given key to get the matching value from
  62165. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62166. * The factory will only be invoked if there's no data for the given key.
  62167. * @return the value corresponding to the key.
  62168. */
  62169. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62170. var val = this.get(key);
  62171. if (val !== undefined) {
  62172. return val;
  62173. }
  62174. val = factory(key);
  62175. if (val) {
  62176. this.add(key, val);
  62177. }
  62178. return val;
  62179. };
  62180. /**
  62181. * Get a value from its key if present in the dictionary otherwise add it
  62182. * @param key the key to get the value from
  62183. * @param val if there's no such key/value pair in the dictionary add it with this value
  62184. * @return the value corresponding to the key
  62185. */
  62186. StringDictionary.prototype.getOrAdd = function (key, val) {
  62187. var curVal = this.get(key);
  62188. if (curVal !== undefined) {
  62189. return curVal;
  62190. }
  62191. this.add(key, val);
  62192. return val;
  62193. };
  62194. /**
  62195. * Check if there's a given key in the dictionary
  62196. * @param key the key to check for
  62197. * @return true if the key is present, false otherwise
  62198. */
  62199. StringDictionary.prototype.contains = function (key) {
  62200. return this._data[key] !== undefined;
  62201. };
  62202. /**
  62203. * Add a new key and its corresponding value
  62204. * @param key the key to add
  62205. * @param value the value corresponding to the key
  62206. * @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
  62207. */
  62208. StringDictionary.prototype.add = function (key, value) {
  62209. if (this._data[key] !== undefined) {
  62210. return false;
  62211. }
  62212. this._data[key] = value;
  62213. ++this._count;
  62214. return true;
  62215. };
  62216. StringDictionary.prototype.set = function (key, value) {
  62217. if (this._data[key] === undefined) {
  62218. return false;
  62219. }
  62220. this._data[key] = value;
  62221. return true;
  62222. };
  62223. /**
  62224. * Get the element of the given key and remove it from the dictionary
  62225. * @param key
  62226. */
  62227. StringDictionary.prototype.getAndRemove = function (key) {
  62228. var val = this.get(key);
  62229. if (val !== undefined) {
  62230. delete this._data[key];
  62231. --this._count;
  62232. return val;
  62233. }
  62234. return null;
  62235. };
  62236. /**
  62237. * Remove a key/value from the dictionary.
  62238. * @param key the key to remove
  62239. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62240. */
  62241. StringDictionary.prototype.remove = function (key) {
  62242. if (this.contains(key)) {
  62243. delete this._data[key];
  62244. --this._count;
  62245. return true;
  62246. }
  62247. return false;
  62248. };
  62249. /**
  62250. * Clear the whole content of the dictionary
  62251. */
  62252. StringDictionary.prototype.clear = function () {
  62253. this._data = {};
  62254. this._count = 0;
  62255. };
  62256. Object.defineProperty(StringDictionary.prototype, "count", {
  62257. get: function () {
  62258. return this._count;
  62259. },
  62260. enumerable: true,
  62261. configurable: true
  62262. });
  62263. /**
  62264. * Execute a callback on each key/val of the dictionary.
  62265. * Note that you can remove any element in this dictionary in the callback implementation
  62266. * @param callback the callback to execute on a given key/value pair
  62267. */
  62268. StringDictionary.prototype.forEach = function (callback) {
  62269. for (var cur in this._data) {
  62270. var val = this._data[cur];
  62271. callback(cur, val);
  62272. }
  62273. };
  62274. /**
  62275. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62276. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62277. * Note that you can remove any element in this dictionary in the callback implementation
  62278. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62279. */
  62280. StringDictionary.prototype.first = function (callback) {
  62281. for (var cur in this._data) {
  62282. var val = this._data[cur];
  62283. var res = callback(cur, val);
  62284. if (res) {
  62285. return res;
  62286. }
  62287. }
  62288. return null;
  62289. };
  62290. return StringDictionary;
  62291. }());
  62292. BABYLON.StringDictionary = StringDictionary;
  62293. })(BABYLON || (BABYLON = {}));
  62294. //# sourceMappingURL=babylon.stringDictionary.js.map
  62295. var BABYLON;
  62296. (function (BABYLON) {
  62297. var Tags = /** @class */ (function () {
  62298. function Tags() {
  62299. }
  62300. Tags.EnableFor = function (obj) {
  62301. obj._tags = obj._tags || {};
  62302. obj.hasTags = function () {
  62303. return Tags.HasTags(obj);
  62304. };
  62305. obj.addTags = function (tagsString) {
  62306. return Tags.AddTagsTo(obj, tagsString);
  62307. };
  62308. obj.removeTags = function (tagsString) {
  62309. return Tags.RemoveTagsFrom(obj, tagsString);
  62310. };
  62311. obj.matchesTagsQuery = function (tagsQuery) {
  62312. return Tags.MatchesQuery(obj, tagsQuery);
  62313. };
  62314. };
  62315. Tags.DisableFor = function (obj) {
  62316. delete obj._tags;
  62317. delete obj.hasTags;
  62318. delete obj.addTags;
  62319. delete obj.removeTags;
  62320. delete obj.matchesTagsQuery;
  62321. };
  62322. Tags.HasTags = function (obj) {
  62323. if (!obj._tags) {
  62324. return false;
  62325. }
  62326. return !BABYLON.Tools.IsEmpty(obj._tags);
  62327. };
  62328. Tags.GetTags = function (obj, asString) {
  62329. if (asString === void 0) { asString = true; }
  62330. if (!obj._tags) {
  62331. return null;
  62332. }
  62333. if (asString) {
  62334. var tagsArray = [];
  62335. for (var tag in obj._tags) {
  62336. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62337. tagsArray.push(tag);
  62338. }
  62339. }
  62340. return tagsArray.join(" ");
  62341. }
  62342. else {
  62343. return obj._tags;
  62344. }
  62345. };
  62346. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62347. // a tag cannot start with '||', '&&', and '!'
  62348. // it cannot contain whitespaces
  62349. Tags.AddTagsTo = function (obj, tagsString) {
  62350. if (!tagsString) {
  62351. return;
  62352. }
  62353. if (typeof tagsString !== "string") {
  62354. return;
  62355. }
  62356. var tags = tagsString.split(" ");
  62357. tags.forEach(function (tag, index, array) {
  62358. Tags._AddTagTo(obj, tag);
  62359. });
  62360. };
  62361. Tags._AddTagTo = function (obj, tag) {
  62362. tag = tag.trim();
  62363. if (tag === "" || tag === "true" || tag === "false") {
  62364. return;
  62365. }
  62366. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62367. return;
  62368. }
  62369. Tags.EnableFor(obj);
  62370. obj._tags[tag] = true;
  62371. };
  62372. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62373. if (!Tags.HasTags(obj)) {
  62374. return;
  62375. }
  62376. var tags = tagsString.split(" ");
  62377. for (var t in tags) {
  62378. Tags._RemoveTagFrom(obj, tags[t]);
  62379. }
  62380. };
  62381. Tags._RemoveTagFrom = function (obj, tag) {
  62382. delete obj._tags[tag];
  62383. };
  62384. Tags.MatchesQuery = function (obj, tagsQuery) {
  62385. if (tagsQuery === undefined) {
  62386. return true;
  62387. }
  62388. if (tagsQuery === "") {
  62389. return Tags.HasTags(obj);
  62390. }
  62391. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62392. };
  62393. return Tags;
  62394. }());
  62395. BABYLON.Tags = Tags;
  62396. })(BABYLON || (BABYLON = {}));
  62397. //# sourceMappingURL=babylon.tags.js.map
  62398. var BABYLON;
  62399. (function (BABYLON) {
  62400. var AndOrNotEvaluator = /** @class */ (function () {
  62401. function AndOrNotEvaluator() {
  62402. }
  62403. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62404. if (!query.match(/\([^\(\)]*\)/g)) {
  62405. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62406. }
  62407. else {
  62408. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62409. // remove parenthesis
  62410. r = r.slice(1, r.length - 1);
  62411. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62412. });
  62413. }
  62414. if (query === "true") {
  62415. return true;
  62416. }
  62417. if (query === "false") {
  62418. return false;
  62419. }
  62420. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62421. };
  62422. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62423. evaluateCallback = evaluateCallback || (function (r) {
  62424. return r === "true" ? true : false;
  62425. });
  62426. var result;
  62427. var or = parenthesisContent.split("||");
  62428. for (var i in or) {
  62429. if (or.hasOwnProperty(i)) {
  62430. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62431. var and = ori.split("&&");
  62432. if (and.length > 1) {
  62433. for (var j = 0; j < and.length; ++j) {
  62434. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62435. if (andj !== "true" && andj !== "false") {
  62436. if (andj[0] === "!") {
  62437. result = !evaluateCallback(andj.substring(1));
  62438. }
  62439. else {
  62440. result = evaluateCallback(andj);
  62441. }
  62442. }
  62443. else {
  62444. result = andj === "true" ? true : false;
  62445. }
  62446. if (!result) {
  62447. ori = "false";
  62448. break;
  62449. }
  62450. }
  62451. }
  62452. if (result || ori === "true") {
  62453. result = true;
  62454. break;
  62455. }
  62456. // result equals false (or undefined)
  62457. if (ori !== "true" && ori !== "false") {
  62458. if (ori[0] === "!") {
  62459. result = !evaluateCallback(ori.substring(1));
  62460. }
  62461. else {
  62462. result = evaluateCallback(ori);
  62463. }
  62464. }
  62465. else {
  62466. result = ori === "true" ? true : false;
  62467. }
  62468. }
  62469. }
  62470. // the whole parenthesis scope is replaced by 'true' or 'false'
  62471. return result ? "true" : "false";
  62472. };
  62473. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62474. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62475. // remove whitespaces
  62476. r = r.replace(/[\s]/g, function () { return ""; });
  62477. return r.length % 2 ? "!" : "";
  62478. });
  62479. booleanString = booleanString.trim();
  62480. if (booleanString === "!true") {
  62481. booleanString = "false";
  62482. }
  62483. else if (booleanString === "!false") {
  62484. booleanString = "true";
  62485. }
  62486. return booleanString;
  62487. };
  62488. return AndOrNotEvaluator;
  62489. }());
  62490. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62491. })(BABYLON || (BABYLON = {}));
  62492. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62493. var BABYLON;
  62494. (function (BABYLON) {
  62495. var Database = /** @class */ (function () {
  62496. function Database(urlToScene, callbackManifestChecked) {
  62497. // Handling various flavors of prefixed version of IndexedDB
  62498. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62499. this.callbackManifestChecked = callbackManifestChecked;
  62500. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62501. this.db = null;
  62502. this._enableSceneOffline = false;
  62503. this._enableTexturesOffline = false;
  62504. this.manifestVersionFound = 0;
  62505. this.mustUpdateRessources = false;
  62506. this.hasReachedQuota = false;
  62507. if (!Database.IDBStorageEnabled) {
  62508. this.callbackManifestChecked(true);
  62509. }
  62510. else {
  62511. this.checkManifestFile();
  62512. }
  62513. }
  62514. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62515. get: function () {
  62516. return this._enableSceneOffline;
  62517. },
  62518. enumerable: true,
  62519. configurable: true
  62520. });
  62521. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62522. get: function () {
  62523. return this._enableTexturesOffline;
  62524. },
  62525. enumerable: true,
  62526. configurable: true
  62527. });
  62528. Database.prototype.checkManifestFile = function () {
  62529. var _this = this;
  62530. var noManifestFile = function () {
  62531. _this._enableSceneOffline = false;
  62532. _this._enableTexturesOffline = false;
  62533. _this.callbackManifestChecked(false);
  62534. };
  62535. var timeStampUsed = false;
  62536. var manifestURL = this.currentSceneUrl + ".manifest";
  62537. var xhr = new XMLHttpRequest();
  62538. if (navigator.onLine) {
  62539. // Adding a timestamp to by-pass browsers' cache
  62540. timeStampUsed = true;
  62541. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62542. }
  62543. xhr.open("GET", manifestURL, true);
  62544. xhr.addEventListener("load", function () {
  62545. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62546. try {
  62547. var manifestFile = JSON.parse(xhr.response);
  62548. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62549. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62550. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62551. _this.manifestVersionFound = manifestFile.version;
  62552. }
  62553. if (_this.callbackManifestChecked) {
  62554. _this.callbackManifestChecked(true);
  62555. }
  62556. }
  62557. catch (ex) {
  62558. noManifestFile();
  62559. }
  62560. }
  62561. else {
  62562. noManifestFile();
  62563. }
  62564. }, false);
  62565. xhr.addEventListener("error", function (event) {
  62566. if (timeStampUsed) {
  62567. timeStampUsed = false;
  62568. // Let's retry without the timeStamp
  62569. // It could fail when coupled with HTML5 Offline API
  62570. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62571. xhr.open("GET", retryManifestURL, true);
  62572. xhr.send();
  62573. }
  62574. else {
  62575. noManifestFile();
  62576. }
  62577. }, false);
  62578. try {
  62579. xhr.send();
  62580. }
  62581. catch (ex) {
  62582. BABYLON.Tools.Error("Error on XHR send request.");
  62583. this.callbackManifestChecked(false);
  62584. }
  62585. };
  62586. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62587. var _this = this;
  62588. var handleError = function () {
  62589. _this.isSupported = false;
  62590. if (errorCallback)
  62591. errorCallback();
  62592. };
  62593. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62594. // Your browser doesn't support IndexedDB
  62595. this.isSupported = false;
  62596. if (errorCallback)
  62597. errorCallback();
  62598. }
  62599. else {
  62600. // If the DB hasn't been opened or created yet
  62601. if (!this.db) {
  62602. this.hasReachedQuota = false;
  62603. this.isSupported = true;
  62604. var request = this.idbFactory.open("babylonjs", 1);
  62605. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62606. request.onerror = function (event) {
  62607. handleError();
  62608. };
  62609. // executes when a version change transaction cannot complete due to other active transactions
  62610. request.onblocked = function (event) {
  62611. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62612. handleError();
  62613. };
  62614. // DB has been opened successfully
  62615. request.onsuccess = function (event) {
  62616. _this.db = request.result;
  62617. successCallback();
  62618. };
  62619. // Initialization of the DB. Creating Scenes & Textures stores
  62620. request.onupgradeneeded = function (event) {
  62621. _this.db = (event.target).result;
  62622. if (_this.db) {
  62623. try {
  62624. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62625. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62626. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62627. }
  62628. catch (ex) {
  62629. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62630. handleError();
  62631. }
  62632. }
  62633. };
  62634. }
  62635. else {
  62636. if (successCallback)
  62637. successCallback();
  62638. }
  62639. }
  62640. };
  62641. Database.prototype.loadImageFromDB = function (url, image) {
  62642. var _this = this;
  62643. var completeURL = Database.ReturnFullUrlLocation(url);
  62644. var saveAndLoadImage = function () {
  62645. if (!_this.hasReachedQuota && _this.db !== null) {
  62646. // the texture is not yet in the DB, let's try to save it
  62647. _this._saveImageIntoDBAsync(completeURL, image);
  62648. }
  62649. else {
  62650. image.src = url;
  62651. }
  62652. };
  62653. if (!this.mustUpdateRessources) {
  62654. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62655. }
  62656. else {
  62657. saveAndLoadImage();
  62658. }
  62659. };
  62660. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62661. if (this.isSupported && this.db !== null) {
  62662. var texture;
  62663. var transaction = this.db.transaction(["textures"]);
  62664. transaction.onabort = function (event) {
  62665. image.src = url;
  62666. };
  62667. transaction.oncomplete = function (event) {
  62668. var blobTextureURL;
  62669. if (texture) {
  62670. var URL = window.URL || window.webkitURL;
  62671. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62672. image.onerror = function () {
  62673. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62674. image.src = url;
  62675. };
  62676. image.src = blobTextureURL;
  62677. }
  62678. else {
  62679. notInDBCallback();
  62680. }
  62681. };
  62682. var getRequest = transaction.objectStore("textures").get(url);
  62683. getRequest.onsuccess = function (event) {
  62684. texture = (event.target).result;
  62685. };
  62686. getRequest.onerror = function (event) {
  62687. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62688. image.src = url;
  62689. };
  62690. }
  62691. else {
  62692. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62693. image.src = url;
  62694. }
  62695. };
  62696. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62697. var _this = this;
  62698. if (this.isSupported) {
  62699. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62700. var generateBlobUrl = function () {
  62701. var blobTextureURL;
  62702. if (blob) {
  62703. var URL = window.URL || window.webkitURL;
  62704. try {
  62705. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62706. }
  62707. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62708. catch (ex) {
  62709. blobTextureURL = URL.createObjectURL(blob);
  62710. }
  62711. }
  62712. if (blobTextureURL) {
  62713. image.src = blobTextureURL;
  62714. }
  62715. };
  62716. if (Database.IsUASupportingBlobStorage) {
  62717. var xhr = new XMLHttpRequest(), blob;
  62718. xhr.open("GET", url, true);
  62719. xhr.responseType = "blob";
  62720. xhr.addEventListener("load", function () {
  62721. if (xhr.status === 200 && _this.db) {
  62722. // Blob as response (XHR2)
  62723. blob = xhr.response;
  62724. var transaction = _this.db.transaction(["textures"], "readwrite");
  62725. // the transaction could abort because of a QuotaExceededError error
  62726. transaction.onabort = function (event) {
  62727. try {
  62728. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62729. var srcElement = (event.srcElement || event.target);
  62730. var error = srcElement.error;
  62731. if (error && error.name === "QuotaExceededError") {
  62732. _this.hasReachedQuota = true;
  62733. }
  62734. }
  62735. catch (ex) { }
  62736. generateBlobUrl();
  62737. };
  62738. transaction.oncomplete = function (event) {
  62739. generateBlobUrl();
  62740. };
  62741. var newTexture = { textureUrl: url, data: blob };
  62742. try {
  62743. // Put the blob into the dabase
  62744. var addRequest = transaction.objectStore("textures").put(newTexture);
  62745. addRequest.onsuccess = function (event) {
  62746. };
  62747. addRequest.onerror = function (event) {
  62748. generateBlobUrl();
  62749. };
  62750. }
  62751. catch (ex) {
  62752. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62753. if (ex.code === 25) {
  62754. Database.IsUASupportingBlobStorage = false;
  62755. }
  62756. image.src = url;
  62757. }
  62758. }
  62759. else {
  62760. image.src = url;
  62761. }
  62762. }, false);
  62763. xhr.addEventListener("error", function (event) {
  62764. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62765. image.src = url;
  62766. }, false);
  62767. xhr.send();
  62768. }
  62769. else {
  62770. image.src = url;
  62771. }
  62772. }
  62773. else {
  62774. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62775. image.src = url;
  62776. }
  62777. };
  62778. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62779. var _this = this;
  62780. var updateVersion = function () {
  62781. // the version is not yet in the DB or we need to update it
  62782. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62783. };
  62784. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62785. };
  62786. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62787. var _this = this;
  62788. if (this.isSupported && this.db) {
  62789. var version;
  62790. try {
  62791. var transaction = this.db.transaction(["versions"]);
  62792. transaction.oncomplete = function (event) {
  62793. if (version) {
  62794. // If the version in the JSON file is > than the version in DB
  62795. if (_this.manifestVersionFound > version.data) {
  62796. _this.mustUpdateRessources = true;
  62797. updateInDBCallback();
  62798. }
  62799. else {
  62800. callback(version.data);
  62801. }
  62802. }
  62803. else {
  62804. _this.mustUpdateRessources = true;
  62805. updateInDBCallback();
  62806. }
  62807. };
  62808. transaction.onabort = function (event) {
  62809. callback(-1);
  62810. };
  62811. var getRequest = transaction.objectStore("versions").get(url);
  62812. getRequest.onsuccess = function (event) {
  62813. version = (event.target).result;
  62814. };
  62815. getRequest.onerror = function (event) {
  62816. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62817. callback(-1);
  62818. };
  62819. }
  62820. catch (ex) {
  62821. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62822. callback(-1);
  62823. }
  62824. }
  62825. else {
  62826. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62827. callback(-1);
  62828. }
  62829. };
  62830. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62831. var _this = this;
  62832. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62833. try {
  62834. // Open a transaction to the database
  62835. var transaction = this.db.transaction(["versions"], "readwrite");
  62836. // the transaction could abort because of a QuotaExceededError error
  62837. transaction.onabort = function (event) {
  62838. try {
  62839. var error = event.srcElement['error'];
  62840. if (error && error.name === "QuotaExceededError") {
  62841. _this.hasReachedQuota = true;
  62842. }
  62843. }
  62844. catch (ex) { }
  62845. callback(-1);
  62846. };
  62847. transaction.oncomplete = function (event) {
  62848. callback(_this.manifestVersionFound);
  62849. };
  62850. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62851. // Put the scene into the database
  62852. var addRequest = transaction.objectStore("versions").put(newVersion);
  62853. addRequest.onsuccess = function (event) {
  62854. };
  62855. addRequest.onerror = function (event) {
  62856. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62857. };
  62858. }
  62859. catch (ex) {
  62860. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62861. callback(-1);
  62862. }
  62863. }
  62864. else {
  62865. callback(-1);
  62866. }
  62867. };
  62868. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62869. var _this = this;
  62870. var completeUrl = Database.ReturnFullUrlLocation(url);
  62871. var saveAndLoadFile = function () {
  62872. // the scene is not yet in the DB, let's try to save it
  62873. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62874. };
  62875. this._checkVersionFromDB(completeUrl, function (version) {
  62876. if (version !== -1) {
  62877. if (!_this.mustUpdateRessources) {
  62878. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62879. }
  62880. else {
  62881. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62882. }
  62883. }
  62884. else {
  62885. if (errorCallback) {
  62886. errorCallback();
  62887. }
  62888. }
  62889. });
  62890. };
  62891. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62892. if (this.isSupported && this.db) {
  62893. var targetStore;
  62894. if (url.indexOf(".babylon") !== -1) {
  62895. targetStore = "scenes";
  62896. }
  62897. else {
  62898. targetStore = "textures";
  62899. }
  62900. var file;
  62901. var transaction = this.db.transaction([targetStore]);
  62902. transaction.oncomplete = function (event) {
  62903. if (file) {
  62904. callback(file.data);
  62905. }
  62906. else {
  62907. notInDBCallback();
  62908. }
  62909. };
  62910. transaction.onabort = function (event) {
  62911. notInDBCallback();
  62912. };
  62913. var getRequest = transaction.objectStore(targetStore).get(url);
  62914. getRequest.onsuccess = function (event) {
  62915. file = (event.target).result;
  62916. };
  62917. getRequest.onerror = function (event) {
  62918. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62919. notInDBCallback();
  62920. };
  62921. }
  62922. else {
  62923. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62924. callback();
  62925. }
  62926. };
  62927. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62928. var _this = this;
  62929. if (this.isSupported) {
  62930. var targetStore;
  62931. if (url.indexOf(".babylon") !== -1) {
  62932. targetStore = "scenes";
  62933. }
  62934. else {
  62935. targetStore = "textures";
  62936. }
  62937. // Create XHR
  62938. var xhr = new XMLHttpRequest();
  62939. var fileData;
  62940. xhr.open("GET", url, true);
  62941. if (useArrayBuffer) {
  62942. xhr.responseType = "arraybuffer";
  62943. }
  62944. if (progressCallback) {
  62945. xhr.onprogress = progressCallback;
  62946. }
  62947. xhr.addEventListener("load", function () {
  62948. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62949. // Blob as response (XHR2)
  62950. //fileData = xhr.responseText;
  62951. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62952. if (!_this.hasReachedQuota && _this.db) {
  62953. // Open a transaction to the database
  62954. var transaction = _this.db.transaction([targetStore], "readwrite");
  62955. // the transaction could abort because of a QuotaExceededError error
  62956. transaction.onabort = function (event) {
  62957. try {
  62958. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62959. var error = event.srcElement['error'];
  62960. if (error && error.name === "QuotaExceededError") {
  62961. _this.hasReachedQuota = true;
  62962. }
  62963. }
  62964. catch (ex) { }
  62965. callback(fileData);
  62966. };
  62967. transaction.oncomplete = function (event) {
  62968. callback(fileData);
  62969. };
  62970. var newFile;
  62971. if (targetStore === "scenes") {
  62972. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62973. }
  62974. else {
  62975. newFile = { textureUrl: url, data: fileData };
  62976. }
  62977. try {
  62978. // Put the scene into the database
  62979. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62980. addRequest.onsuccess = function (event) {
  62981. };
  62982. addRequest.onerror = function (event) {
  62983. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62984. };
  62985. }
  62986. catch (ex) {
  62987. callback(fileData);
  62988. }
  62989. }
  62990. else {
  62991. callback(fileData);
  62992. }
  62993. }
  62994. else {
  62995. callback();
  62996. }
  62997. }, false);
  62998. xhr.addEventListener("error", function (event) {
  62999. BABYLON.Tools.Error("error on XHR request.");
  63000. callback();
  63001. }, false);
  63002. xhr.send();
  63003. }
  63004. else {
  63005. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63006. callback();
  63007. }
  63008. };
  63009. Database.IsUASupportingBlobStorage = true;
  63010. Database.IDBStorageEnabled = true;
  63011. Database.parseURL = function (url) {
  63012. var a = document.createElement('a');
  63013. a.href = url;
  63014. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63015. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63016. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63017. return absLocation;
  63018. };
  63019. Database.ReturnFullUrlLocation = function (url) {
  63020. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63021. return (Database.parseURL(window.location.href) + url);
  63022. }
  63023. else {
  63024. return url;
  63025. }
  63026. };
  63027. return Database;
  63028. }());
  63029. BABYLON.Database = Database;
  63030. })(BABYLON || (BABYLON = {}));
  63031. //# sourceMappingURL=babylon.database.js.map
  63032. var BABYLON;
  63033. (function (BABYLON) {
  63034. var FresnelParameters = /** @class */ (function () {
  63035. function FresnelParameters() {
  63036. this._isEnabled = true;
  63037. this.leftColor = BABYLON.Color3.White();
  63038. this.rightColor = BABYLON.Color3.Black();
  63039. this.bias = 0;
  63040. this.power = 1;
  63041. }
  63042. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63043. get: function () {
  63044. return this._isEnabled;
  63045. },
  63046. set: function (value) {
  63047. if (this._isEnabled === value) {
  63048. return;
  63049. }
  63050. this._isEnabled = value;
  63051. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63052. },
  63053. enumerable: true,
  63054. configurable: true
  63055. });
  63056. FresnelParameters.prototype.clone = function () {
  63057. var newFresnelParameters = new FresnelParameters();
  63058. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63059. return newFresnelParameters;
  63060. };
  63061. FresnelParameters.prototype.serialize = function () {
  63062. var serializationObject = {};
  63063. serializationObject.isEnabled = this.isEnabled;
  63064. serializationObject.leftColor = this.leftColor;
  63065. serializationObject.rightColor = this.rightColor;
  63066. serializationObject.bias = this.bias;
  63067. serializationObject.power = this.power;
  63068. return serializationObject;
  63069. };
  63070. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63071. var fresnelParameters = new FresnelParameters();
  63072. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63073. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63074. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63075. fresnelParameters.bias = parsedFresnelParameters.bias;
  63076. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63077. return fresnelParameters;
  63078. };
  63079. return FresnelParameters;
  63080. }());
  63081. BABYLON.FresnelParameters = FresnelParameters;
  63082. })(BABYLON || (BABYLON = {}));
  63083. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63084. var BABYLON;
  63085. (function (BABYLON) {
  63086. var MultiMaterial = /** @class */ (function (_super) {
  63087. __extends(MultiMaterial, _super);
  63088. function MultiMaterial(name, scene) {
  63089. var _this = _super.call(this, name, scene, true) || this;
  63090. scene.multiMaterials.push(_this);
  63091. _this.subMaterials = new Array();
  63092. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63093. return _this;
  63094. }
  63095. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63096. get: function () {
  63097. return this._subMaterials;
  63098. },
  63099. set: function (value) {
  63100. this._subMaterials = value;
  63101. this._hookArray(value);
  63102. },
  63103. enumerable: true,
  63104. configurable: true
  63105. });
  63106. MultiMaterial.prototype._hookArray = function (array) {
  63107. var _this = this;
  63108. var oldPush = array.push;
  63109. array.push = function () {
  63110. var items = [];
  63111. for (var _i = 0; _i < arguments.length; _i++) {
  63112. items[_i] = arguments[_i];
  63113. }
  63114. var result = oldPush.apply(array, items);
  63115. _this._markAllSubMeshesAsTexturesDirty();
  63116. return result;
  63117. };
  63118. var oldSplice = array.splice;
  63119. array.splice = function (index, deleteCount) {
  63120. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63121. _this._markAllSubMeshesAsTexturesDirty();
  63122. return deleted;
  63123. };
  63124. };
  63125. // Properties
  63126. MultiMaterial.prototype.getSubMaterial = function (index) {
  63127. if (index < 0 || index >= this.subMaterials.length) {
  63128. return this.getScene().defaultMaterial;
  63129. }
  63130. return this.subMaterials[index];
  63131. };
  63132. MultiMaterial.prototype.getActiveTextures = function () {
  63133. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63134. if (subMaterial) {
  63135. return subMaterial.getActiveTextures();
  63136. }
  63137. else {
  63138. return [];
  63139. }
  63140. }));
  63141. var _a;
  63142. };
  63143. // Methods
  63144. MultiMaterial.prototype.getClassName = function () {
  63145. return "MultiMaterial";
  63146. };
  63147. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63148. for (var index = 0; index < this.subMaterials.length; index++) {
  63149. var subMaterial = this.subMaterials[index];
  63150. if (subMaterial) {
  63151. if (subMaterial.storeEffectOnSubMeshes) {
  63152. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63153. return false;
  63154. }
  63155. continue;
  63156. }
  63157. if (!subMaterial.isReady(mesh)) {
  63158. return false;
  63159. }
  63160. }
  63161. }
  63162. return true;
  63163. };
  63164. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63165. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63166. for (var index = 0; index < this.subMaterials.length; index++) {
  63167. var subMaterial = null;
  63168. var current = this.subMaterials[index];
  63169. if (cloneChildren && current) {
  63170. subMaterial = current.clone(name + "-" + current.name);
  63171. }
  63172. else {
  63173. subMaterial = this.subMaterials[index];
  63174. }
  63175. newMultiMaterial.subMaterials.push(subMaterial);
  63176. }
  63177. return newMultiMaterial;
  63178. };
  63179. MultiMaterial.prototype.serialize = function () {
  63180. var serializationObject = {};
  63181. serializationObject.name = this.name;
  63182. serializationObject.id = this.id;
  63183. if (BABYLON.Tags) {
  63184. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63185. }
  63186. serializationObject.materials = [];
  63187. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63188. var subMat = this.subMaterials[matIndex];
  63189. if (subMat) {
  63190. serializationObject.materials.push(subMat.id);
  63191. }
  63192. else {
  63193. serializationObject.materials.push(null);
  63194. }
  63195. }
  63196. return serializationObject;
  63197. };
  63198. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63199. var scene = this.getScene();
  63200. if (!scene) {
  63201. return;
  63202. }
  63203. var index = scene.multiMaterials.indexOf(this);
  63204. if (index >= 0) {
  63205. scene.multiMaterials.splice(index, 1);
  63206. }
  63207. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63208. };
  63209. return MultiMaterial;
  63210. }(BABYLON.Material));
  63211. BABYLON.MultiMaterial = MultiMaterial;
  63212. })(BABYLON || (BABYLON = {}));
  63213. //# sourceMappingURL=babylon.multiMaterial.js.map
  63214. var BABYLON;
  63215. (function (BABYLON) {
  63216. var FreeCameraTouchInput = /** @class */ (function () {
  63217. function FreeCameraTouchInput() {
  63218. this._offsetX = null;
  63219. this._offsetY = null;
  63220. this._pointerPressed = new Array();
  63221. this.touchAngularSensibility = 200000.0;
  63222. this.touchMoveSensibility = 250.0;
  63223. }
  63224. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63225. var _this = this;
  63226. var previousPosition = null;
  63227. if (this._pointerInput === undefined) {
  63228. this._onLostFocus = function (evt) {
  63229. _this._offsetX = null;
  63230. _this._offsetY = null;
  63231. };
  63232. this._pointerInput = function (p, s) {
  63233. var evt = p.event;
  63234. if (evt.pointerType === "mouse") {
  63235. return;
  63236. }
  63237. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63238. if (!noPreventDefault) {
  63239. evt.preventDefault();
  63240. }
  63241. _this._pointerPressed.push(evt.pointerId);
  63242. if (_this._pointerPressed.length !== 1) {
  63243. return;
  63244. }
  63245. previousPosition = {
  63246. x: evt.clientX,
  63247. y: evt.clientY
  63248. };
  63249. }
  63250. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63251. if (!noPreventDefault) {
  63252. evt.preventDefault();
  63253. }
  63254. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63255. if (index === -1) {
  63256. return;
  63257. }
  63258. _this._pointerPressed.splice(index, 1);
  63259. if (index != 0) {
  63260. return;
  63261. }
  63262. previousPosition = null;
  63263. _this._offsetX = null;
  63264. _this._offsetY = null;
  63265. }
  63266. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63267. if (!noPreventDefault) {
  63268. evt.preventDefault();
  63269. }
  63270. if (!previousPosition) {
  63271. return;
  63272. }
  63273. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63274. if (index != 0) {
  63275. return;
  63276. }
  63277. _this._offsetX = evt.clientX - previousPosition.x;
  63278. _this._offsetY = -(evt.clientY - previousPosition.y);
  63279. }
  63280. };
  63281. }
  63282. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63283. if (this._onLostFocus) {
  63284. element.addEventListener("blur", this._onLostFocus);
  63285. }
  63286. };
  63287. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63288. if (this._pointerInput && element) {
  63289. if (this._observer) {
  63290. this.camera.getScene().onPointerObservable.remove(this._observer);
  63291. this._observer = null;
  63292. }
  63293. if (this._onLostFocus) {
  63294. element.removeEventListener("blur", this._onLostFocus);
  63295. this._onLostFocus = null;
  63296. }
  63297. this._pointerPressed = [];
  63298. this._offsetX = null;
  63299. this._offsetY = null;
  63300. }
  63301. };
  63302. FreeCameraTouchInput.prototype.checkInputs = function () {
  63303. if (this._offsetX && this._offsetY) {
  63304. var camera = this.camera;
  63305. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63306. if (this._pointerPressed.length > 1) {
  63307. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63308. }
  63309. else {
  63310. var speed = camera._computeLocalCameraSpeed();
  63311. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63312. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63313. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63314. }
  63315. }
  63316. };
  63317. FreeCameraTouchInput.prototype.getClassName = function () {
  63318. return "FreeCameraTouchInput";
  63319. };
  63320. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63321. return "touch";
  63322. };
  63323. __decorate([
  63324. BABYLON.serialize()
  63325. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63326. __decorate([
  63327. BABYLON.serialize()
  63328. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63329. return FreeCameraTouchInput;
  63330. }());
  63331. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63332. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63333. })(BABYLON || (BABYLON = {}));
  63334. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63335. var BABYLON;
  63336. (function (BABYLON) {
  63337. // We're mainly based on the logic defined into the FreeCamera code
  63338. var TouchCamera = /** @class */ (function (_super) {
  63339. __extends(TouchCamera, _super);
  63340. //-- end properties for backward compatibility for inputs
  63341. function TouchCamera(name, position, scene) {
  63342. var _this = _super.call(this, name, position, scene) || this;
  63343. _this.inputs.addTouch();
  63344. _this._setupInputs();
  63345. return _this;
  63346. }
  63347. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63348. //-- Begin properties for backward compatibility for inputs
  63349. get: function () {
  63350. var touch = this.inputs.attached["touch"];
  63351. if (touch)
  63352. return touch.touchAngularSensibility;
  63353. return 0;
  63354. },
  63355. set: function (value) {
  63356. var touch = this.inputs.attached["touch"];
  63357. if (touch)
  63358. touch.touchAngularSensibility = value;
  63359. },
  63360. enumerable: true,
  63361. configurable: true
  63362. });
  63363. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63364. get: function () {
  63365. var touch = this.inputs.attached["touch"];
  63366. if (touch)
  63367. return touch.touchMoveSensibility;
  63368. return 0;
  63369. },
  63370. set: function (value) {
  63371. var touch = this.inputs.attached["touch"];
  63372. if (touch)
  63373. touch.touchMoveSensibility = value;
  63374. },
  63375. enumerable: true,
  63376. configurable: true
  63377. });
  63378. TouchCamera.prototype.getClassName = function () {
  63379. return "TouchCamera";
  63380. };
  63381. TouchCamera.prototype._setupInputs = function () {
  63382. var mouse = this.inputs.attached["mouse"];
  63383. if (mouse) {
  63384. mouse.touchEnabled = false;
  63385. }
  63386. };
  63387. return TouchCamera;
  63388. }(BABYLON.FreeCamera));
  63389. BABYLON.TouchCamera = TouchCamera;
  63390. })(BABYLON || (BABYLON = {}));
  63391. //# sourceMappingURL=babylon.touchCamera.js.map
  63392. var BABYLON;
  63393. (function (BABYLON) {
  63394. var ProceduralTexture = /** @class */ (function (_super) {
  63395. __extends(ProceduralTexture, _super);
  63396. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63397. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63398. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63399. if (isCube === void 0) { isCube = false; }
  63400. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63401. _this.isCube = isCube;
  63402. _this.isEnabled = true;
  63403. _this._currentRefreshId = -1;
  63404. _this._refreshRate = 1;
  63405. _this._vertexBuffers = {};
  63406. _this._uniforms = new Array();
  63407. _this._samplers = new Array();
  63408. _this._textures = {};
  63409. _this._floats = {};
  63410. _this._floatsArrays = {};
  63411. _this._colors3 = {};
  63412. _this._colors4 = {};
  63413. _this._vectors2 = {};
  63414. _this._vectors3 = {};
  63415. _this._matrices = {};
  63416. _this._fallbackTextureUsed = false;
  63417. scene._proceduralTextures.push(_this);
  63418. _this._engine = scene.getEngine();
  63419. _this.name = name;
  63420. _this.isRenderTarget = true;
  63421. _this._size = size;
  63422. _this._generateMipMaps = generateMipMaps;
  63423. _this.setFragment(fragment);
  63424. _this._fallbackTexture = fallbackTexture;
  63425. if (isCube) {
  63426. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63427. _this.setFloat("face", 0);
  63428. }
  63429. else {
  63430. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63431. }
  63432. // VBO
  63433. var vertices = [];
  63434. vertices.push(1, 1);
  63435. vertices.push(-1, 1);
  63436. vertices.push(-1, -1);
  63437. vertices.push(1, -1);
  63438. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63439. _this._createIndexBuffer();
  63440. return _this;
  63441. }
  63442. ProceduralTexture.prototype._createIndexBuffer = function () {
  63443. var engine = this._engine;
  63444. // Indices
  63445. var indices = [];
  63446. indices.push(0);
  63447. indices.push(1);
  63448. indices.push(2);
  63449. indices.push(0);
  63450. indices.push(2);
  63451. indices.push(3);
  63452. this._indexBuffer = engine.createIndexBuffer(indices);
  63453. };
  63454. ProceduralTexture.prototype._rebuild = function () {
  63455. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63456. if (vb) {
  63457. vb._rebuild();
  63458. }
  63459. this._createIndexBuffer();
  63460. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63461. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63462. }
  63463. };
  63464. ProceduralTexture.prototype.reset = function () {
  63465. if (this._effect === undefined) {
  63466. return;
  63467. }
  63468. var engine = this._engine;
  63469. engine._releaseEffect(this._effect);
  63470. };
  63471. ProceduralTexture.prototype.isReady = function () {
  63472. var _this = this;
  63473. var engine = this._engine;
  63474. var shaders;
  63475. if (!this._fragment) {
  63476. return false;
  63477. }
  63478. if (this._fallbackTextureUsed) {
  63479. return true;
  63480. }
  63481. if (this._fragment.fragmentElement !== undefined) {
  63482. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63483. }
  63484. else {
  63485. shaders = { vertex: "procedural", fragment: this._fragment };
  63486. }
  63487. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63488. _this.releaseInternalTexture();
  63489. if (_this._fallbackTexture) {
  63490. _this._texture = _this._fallbackTexture._texture;
  63491. if (_this._texture) {
  63492. _this._texture.incrementReferences();
  63493. }
  63494. }
  63495. _this._fallbackTextureUsed = true;
  63496. });
  63497. return this._effect.isReady();
  63498. };
  63499. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63500. this._currentRefreshId = -1;
  63501. };
  63502. ProceduralTexture.prototype.setFragment = function (fragment) {
  63503. this._fragment = fragment;
  63504. };
  63505. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63506. get: function () {
  63507. return this._refreshRate;
  63508. },
  63509. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63510. set: function (value) {
  63511. this._refreshRate = value;
  63512. this.resetRefreshCounter();
  63513. },
  63514. enumerable: true,
  63515. configurable: true
  63516. });
  63517. ProceduralTexture.prototype._shouldRender = function () {
  63518. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63519. return false;
  63520. }
  63521. if (this._fallbackTextureUsed) {
  63522. return false;
  63523. }
  63524. if (this._currentRefreshId === -1) {
  63525. this._currentRefreshId = 1;
  63526. return true;
  63527. }
  63528. if (this.refreshRate === this._currentRefreshId) {
  63529. this._currentRefreshId = 1;
  63530. return true;
  63531. }
  63532. this._currentRefreshId++;
  63533. return false;
  63534. };
  63535. ProceduralTexture.prototype.getRenderSize = function () {
  63536. return this._size;
  63537. };
  63538. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63539. if (this._fallbackTextureUsed) {
  63540. return;
  63541. }
  63542. this.releaseInternalTexture();
  63543. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63544. };
  63545. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63546. if (this._uniforms.indexOf(uniformName) === -1) {
  63547. this._uniforms.push(uniformName);
  63548. }
  63549. };
  63550. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63551. if (this._samplers.indexOf(name) === -1) {
  63552. this._samplers.push(name);
  63553. }
  63554. this._textures[name] = texture;
  63555. return this;
  63556. };
  63557. ProceduralTexture.prototype.setFloat = function (name, value) {
  63558. this._checkUniform(name);
  63559. this._floats[name] = value;
  63560. return this;
  63561. };
  63562. ProceduralTexture.prototype.setFloats = function (name, value) {
  63563. this._checkUniform(name);
  63564. this._floatsArrays[name] = value;
  63565. return this;
  63566. };
  63567. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63568. this._checkUniform(name);
  63569. this._colors3[name] = value;
  63570. return this;
  63571. };
  63572. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63573. this._checkUniform(name);
  63574. this._colors4[name] = value;
  63575. return this;
  63576. };
  63577. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63578. this._checkUniform(name);
  63579. this._vectors2[name] = value;
  63580. return this;
  63581. };
  63582. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63583. this._checkUniform(name);
  63584. this._vectors3[name] = value;
  63585. return this;
  63586. };
  63587. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63588. this._checkUniform(name);
  63589. this._matrices[name] = value;
  63590. return this;
  63591. };
  63592. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63593. var scene = this.getScene();
  63594. if (!scene) {
  63595. return;
  63596. }
  63597. var engine = this._engine;
  63598. // Render
  63599. engine.enableEffect(this._effect);
  63600. engine.setState(false);
  63601. // Texture
  63602. for (var name in this._textures) {
  63603. this._effect.setTexture(name, this._textures[name]);
  63604. }
  63605. // Float
  63606. for (name in this._floats) {
  63607. this._effect.setFloat(name, this._floats[name]);
  63608. }
  63609. // Floats
  63610. for (name in this._floatsArrays) {
  63611. this._effect.setArray(name, this._floatsArrays[name]);
  63612. }
  63613. // Color3
  63614. for (name in this._colors3) {
  63615. this._effect.setColor3(name, this._colors3[name]);
  63616. }
  63617. // Color4
  63618. for (name in this._colors4) {
  63619. var color = this._colors4[name];
  63620. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63621. }
  63622. // Vector2
  63623. for (name in this._vectors2) {
  63624. this._effect.setVector2(name, this._vectors2[name]);
  63625. }
  63626. // Vector3
  63627. for (name in this._vectors3) {
  63628. this._effect.setVector3(name, this._vectors3[name]);
  63629. }
  63630. // Matrix
  63631. for (name in this._matrices) {
  63632. this._effect.setMatrix(name, this._matrices[name]);
  63633. }
  63634. if (!this._texture) {
  63635. return;
  63636. }
  63637. if (this.isCube) {
  63638. for (var face = 0; face < 6; face++) {
  63639. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63640. // VBOs
  63641. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63642. this._effect.setFloat("face", face);
  63643. // Clear
  63644. engine.clear(scene.clearColor, true, true, true);
  63645. // Draw order
  63646. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63647. // Mipmaps
  63648. if (face === 5) {
  63649. engine.generateMipMapsForCubemap(this._texture);
  63650. }
  63651. }
  63652. }
  63653. else {
  63654. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63655. // VBOs
  63656. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63657. // Clear
  63658. engine.clear(scene.clearColor, true, true, true);
  63659. // Draw order
  63660. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63661. }
  63662. // Unbind
  63663. engine.unBindFramebuffer(this._texture, this.isCube);
  63664. if (this.onGenerated) {
  63665. this.onGenerated();
  63666. }
  63667. };
  63668. ProceduralTexture.prototype.clone = function () {
  63669. var textureSize = this.getSize();
  63670. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63671. // Base texture
  63672. newTexture.hasAlpha = this.hasAlpha;
  63673. newTexture.level = this.level;
  63674. // RenderTarget Texture
  63675. newTexture.coordinatesMode = this.coordinatesMode;
  63676. return newTexture;
  63677. };
  63678. ProceduralTexture.prototype.dispose = function () {
  63679. var scene = this.getScene();
  63680. if (!scene) {
  63681. return;
  63682. }
  63683. var index = scene._proceduralTextures.indexOf(this);
  63684. if (index >= 0) {
  63685. scene._proceduralTextures.splice(index, 1);
  63686. }
  63687. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63688. if (vertexBuffer) {
  63689. vertexBuffer.dispose();
  63690. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63691. }
  63692. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63693. this._indexBuffer = null;
  63694. }
  63695. _super.prototype.dispose.call(this);
  63696. };
  63697. return ProceduralTexture;
  63698. }(BABYLON.Texture));
  63699. BABYLON.ProceduralTexture = ProceduralTexture;
  63700. })(BABYLON || (BABYLON = {}));
  63701. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63702. var BABYLON;
  63703. (function (BABYLON) {
  63704. var CustomProceduralTexture = /** @class */ (function (_super) {
  63705. __extends(CustomProceduralTexture, _super);
  63706. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63707. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63708. _this._animate = true;
  63709. _this._time = 0;
  63710. _this._texturePath = texturePath;
  63711. //Try to load json
  63712. _this.loadJson(texturePath);
  63713. _this.refreshRate = 1;
  63714. return _this;
  63715. }
  63716. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63717. var _this = this;
  63718. var noConfigFile = function () {
  63719. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63720. try {
  63721. _this.setFragment(_this._texturePath);
  63722. }
  63723. catch (ex) {
  63724. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63725. }
  63726. };
  63727. var configFileUrl = jsonUrl + "/config.json";
  63728. var xhr = new XMLHttpRequest();
  63729. xhr.open("GET", configFileUrl, true);
  63730. xhr.addEventListener("load", function () {
  63731. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63732. try {
  63733. _this._config = JSON.parse(xhr.response);
  63734. _this.updateShaderUniforms();
  63735. _this.updateTextures();
  63736. _this.setFragment(_this._texturePath + "/custom");
  63737. _this._animate = _this._config.animate;
  63738. _this.refreshRate = _this._config.refreshrate;
  63739. }
  63740. catch (ex) {
  63741. noConfigFile();
  63742. }
  63743. }
  63744. else {
  63745. noConfigFile();
  63746. }
  63747. }, false);
  63748. xhr.addEventListener("error", function () {
  63749. noConfigFile();
  63750. }, false);
  63751. try {
  63752. xhr.send();
  63753. }
  63754. catch (ex) {
  63755. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63756. }
  63757. };
  63758. CustomProceduralTexture.prototype.isReady = function () {
  63759. if (!_super.prototype.isReady.call(this)) {
  63760. return false;
  63761. }
  63762. for (var name in this._textures) {
  63763. var texture = this._textures[name];
  63764. if (!texture.isReady()) {
  63765. return false;
  63766. }
  63767. }
  63768. return true;
  63769. };
  63770. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63771. var scene = this.getScene();
  63772. if (this._animate && scene) {
  63773. this._time += scene.getAnimationRatio() * 0.03;
  63774. this.updateShaderUniforms();
  63775. }
  63776. _super.prototype.render.call(this, useCameraPostProcess);
  63777. };
  63778. CustomProceduralTexture.prototype.updateTextures = function () {
  63779. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63780. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63781. }
  63782. };
  63783. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63784. if (this._config) {
  63785. for (var j = 0; j < this._config.uniforms.length; j++) {
  63786. var uniform = this._config.uniforms[j];
  63787. switch (uniform.type) {
  63788. case "float":
  63789. this.setFloat(uniform.name, uniform.value);
  63790. break;
  63791. case "color3":
  63792. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63793. break;
  63794. case "color4":
  63795. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63796. break;
  63797. case "vector2":
  63798. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63799. break;
  63800. case "vector3":
  63801. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63802. break;
  63803. }
  63804. }
  63805. }
  63806. this.setFloat("time", this._time);
  63807. };
  63808. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63809. get: function () {
  63810. return this._animate;
  63811. },
  63812. set: function (value) {
  63813. this._animate = value;
  63814. },
  63815. enumerable: true,
  63816. configurable: true
  63817. });
  63818. return CustomProceduralTexture;
  63819. }(BABYLON.ProceduralTexture));
  63820. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63821. })(BABYLON || (BABYLON = {}));
  63822. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63823. var BABYLON;
  63824. (function (BABYLON) {
  63825. var FreeCameraGamepadInput = /** @class */ (function () {
  63826. function FreeCameraGamepadInput() {
  63827. this.gamepadAngularSensibility = 200;
  63828. this.gamepadMoveSensibility = 40;
  63829. // private members
  63830. this._cameraTransform = BABYLON.Matrix.Identity();
  63831. this._deltaTransform = BABYLON.Vector3.Zero();
  63832. this._vector3 = BABYLON.Vector3.Zero();
  63833. this._vector2 = BABYLON.Vector2.Zero();
  63834. }
  63835. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63836. var _this = this;
  63837. var manager = this.camera.getScene().gamepadManager;
  63838. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63839. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63840. // prioritize XBOX gamepads.
  63841. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63842. _this.gamepad = gamepad;
  63843. }
  63844. }
  63845. });
  63846. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63847. if (_this.gamepad === gamepad) {
  63848. _this.gamepad = null;
  63849. }
  63850. });
  63851. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63852. };
  63853. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63854. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63855. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63856. this.gamepad = null;
  63857. };
  63858. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63859. if (this.gamepad && this.gamepad.leftStick) {
  63860. var camera = this.camera;
  63861. var LSValues = this.gamepad.leftStick;
  63862. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63863. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63864. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63865. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63866. var RSValues = this.gamepad.rightStick;
  63867. if (RSValues) {
  63868. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63869. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63870. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63871. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63872. }
  63873. else {
  63874. RSValues = { x: 0, y: 0 };
  63875. }
  63876. if (!camera.rotationQuaternion) {
  63877. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63878. }
  63879. else {
  63880. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63881. }
  63882. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63883. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63884. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63885. camera.cameraDirection.addInPlace(this._deltaTransform);
  63886. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63887. camera.cameraRotation.addInPlace(this._vector2);
  63888. }
  63889. };
  63890. FreeCameraGamepadInput.prototype.getClassName = function () {
  63891. return "FreeCameraGamepadInput";
  63892. };
  63893. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63894. return "gamepad";
  63895. };
  63896. __decorate([
  63897. BABYLON.serialize()
  63898. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63899. __decorate([
  63900. BABYLON.serialize()
  63901. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63902. return FreeCameraGamepadInput;
  63903. }());
  63904. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63905. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63906. })(BABYLON || (BABYLON = {}));
  63907. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63908. var BABYLON;
  63909. (function (BABYLON) {
  63910. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63911. function ArcRotateCameraGamepadInput() {
  63912. this.gamepadRotationSensibility = 80;
  63913. this.gamepadMoveSensibility = 40;
  63914. }
  63915. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63916. var _this = this;
  63917. var manager = this.camera.getScene().gamepadManager;
  63918. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63919. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63920. // prioritize XBOX gamepads.
  63921. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63922. _this.gamepad = gamepad;
  63923. }
  63924. }
  63925. });
  63926. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63927. if (_this.gamepad === gamepad) {
  63928. _this.gamepad = null;
  63929. }
  63930. });
  63931. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63932. };
  63933. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63934. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63935. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63936. this.gamepad = null;
  63937. };
  63938. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63939. if (this.gamepad) {
  63940. var camera = this.camera;
  63941. var RSValues = this.gamepad.rightStick;
  63942. if (RSValues) {
  63943. if (RSValues.x != 0) {
  63944. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63945. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63946. camera.inertialAlphaOffset += normalizedRX;
  63947. }
  63948. }
  63949. if (RSValues.y != 0) {
  63950. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63951. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63952. camera.inertialBetaOffset += normalizedRY;
  63953. }
  63954. }
  63955. }
  63956. var LSValues = this.gamepad.leftStick;
  63957. if (LSValues && LSValues.y != 0) {
  63958. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63959. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63960. this.camera.inertialRadiusOffset -= normalizedLY;
  63961. }
  63962. }
  63963. }
  63964. };
  63965. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63966. return "ArcRotateCameraGamepadInput";
  63967. };
  63968. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63969. return "gamepad";
  63970. };
  63971. __decorate([
  63972. BABYLON.serialize()
  63973. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63974. __decorate([
  63975. BABYLON.serialize()
  63976. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63977. return ArcRotateCameraGamepadInput;
  63978. }());
  63979. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63980. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63981. })(BABYLON || (BABYLON = {}));
  63982. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63983. var BABYLON;
  63984. (function (BABYLON) {
  63985. var GamepadManager = /** @class */ (function () {
  63986. function GamepadManager(_scene) {
  63987. var _this = this;
  63988. this._scene = _scene;
  63989. this._babylonGamepads = [];
  63990. this._oneGamepadConnected = false;
  63991. this._isMonitoring = false;
  63992. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63993. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63994. this._gamepadEventSupported = false;
  63995. }
  63996. else {
  63997. this._gamepadEventSupported = 'GamepadEvent' in window;
  63998. this._gamepadSupport = (navigator.getGamepads ||
  63999. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64000. }
  64001. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64002. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64003. for (var i in _this._babylonGamepads) {
  64004. var gamepad = _this._babylonGamepads[i];
  64005. if (gamepad && gamepad._isConnected) {
  64006. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64007. }
  64008. }
  64009. });
  64010. this._onGamepadConnectedEvent = function (evt) {
  64011. var gamepad = evt.gamepad;
  64012. if (gamepad.index in _this._babylonGamepads) {
  64013. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64014. return;
  64015. }
  64016. }
  64017. var newGamepad;
  64018. if (_this._babylonGamepads[gamepad.index]) {
  64019. newGamepad = _this._babylonGamepads[gamepad.index];
  64020. newGamepad.browserGamepad = gamepad;
  64021. newGamepad._isConnected = true;
  64022. }
  64023. else {
  64024. newGamepad = _this._addNewGamepad(gamepad);
  64025. }
  64026. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64027. _this._startMonitoringGamepads();
  64028. };
  64029. this._onGamepadDisconnectedEvent = function (evt) {
  64030. var gamepad = evt.gamepad;
  64031. // Remove the gamepad from the list of gamepads to monitor.
  64032. for (var i in _this._babylonGamepads) {
  64033. if (_this._babylonGamepads[i].index === gamepad.index) {
  64034. var disconnectedGamepad = _this._babylonGamepads[i];
  64035. disconnectedGamepad._isConnected = false;
  64036. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64037. break;
  64038. }
  64039. }
  64040. };
  64041. if (this._gamepadSupport) {
  64042. //first add already-connected gamepads
  64043. this._updateGamepadObjects();
  64044. if (this._babylonGamepads.length) {
  64045. this._startMonitoringGamepads();
  64046. }
  64047. // Checking if the gamepad connected event is supported (like in Firefox)
  64048. if (this._gamepadEventSupported) {
  64049. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64050. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64051. }
  64052. else {
  64053. this._startMonitoringGamepads();
  64054. }
  64055. }
  64056. }
  64057. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64058. get: function () {
  64059. return this._babylonGamepads;
  64060. },
  64061. enumerable: true,
  64062. configurable: true
  64063. });
  64064. GamepadManager.prototype.getGamepadByType = function (type) {
  64065. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64066. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64067. var gamepad = _a[_i];
  64068. if (gamepad && gamepad.type === type) {
  64069. return gamepad;
  64070. }
  64071. }
  64072. return null;
  64073. };
  64074. GamepadManager.prototype.dispose = function () {
  64075. if (this._gamepadEventSupported) {
  64076. if (this._onGamepadConnectedEvent) {
  64077. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64078. }
  64079. if (this._onGamepadDisconnectedEvent) {
  64080. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64081. }
  64082. this._onGamepadConnectedEvent = null;
  64083. this._onGamepadDisconnectedEvent = null;
  64084. }
  64085. this._babylonGamepads.forEach(function (gamepad) {
  64086. gamepad.dispose();
  64087. });
  64088. this.onGamepadConnectedObservable.clear();
  64089. this.onGamepadDisconnectedObservable.clear();
  64090. this._oneGamepadConnected = false;
  64091. this._stopMonitoringGamepads();
  64092. this._babylonGamepads = [];
  64093. };
  64094. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64095. if (!this._oneGamepadConnected) {
  64096. this._oneGamepadConnected = true;
  64097. }
  64098. var newGamepad;
  64099. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64100. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64101. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64102. }
  64103. else if (gamepad.pose) {
  64104. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64105. }
  64106. else {
  64107. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64108. }
  64109. this._babylonGamepads[newGamepad.index] = newGamepad;
  64110. return newGamepad;
  64111. };
  64112. GamepadManager.prototype._startMonitoringGamepads = function () {
  64113. if (!this._isMonitoring) {
  64114. this._isMonitoring = true;
  64115. //back-comp
  64116. if (!this._scene) {
  64117. this._checkGamepadsStatus();
  64118. }
  64119. }
  64120. };
  64121. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64122. this._isMonitoring = false;
  64123. };
  64124. GamepadManager.prototype._checkGamepadsStatus = function () {
  64125. var _this = this;
  64126. // Hack to be compatible Chrome
  64127. this._updateGamepadObjects();
  64128. for (var i in this._babylonGamepads) {
  64129. var gamepad = this._babylonGamepads[i];
  64130. if (!gamepad || !gamepad.isConnected) {
  64131. continue;
  64132. }
  64133. gamepad.update();
  64134. }
  64135. if (this._isMonitoring && !this._scene) {
  64136. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64137. }
  64138. };
  64139. // This function is called only on Chrome, which does not properly support
  64140. // connection/disconnection events and forces you to recopy again the gamepad object
  64141. GamepadManager.prototype._updateGamepadObjects = function () {
  64142. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64143. for (var i = 0; i < gamepads.length; i++) {
  64144. if (gamepads[i]) {
  64145. if (!this._babylonGamepads[gamepads[i].index]) {
  64146. var newGamepad = this._addNewGamepad(gamepads[i]);
  64147. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64148. }
  64149. else {
  64150. // Forced to copy again this object for Chrome for unknown reason
  64151. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64152. if (!this._babylonGamepads[i].isConnected) {
  64153. this._babylonGamepads[i]._isConnected = true;
  64154. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64155. }
  64156. }
  64157. }
  64158. }
  64159. };
  64160. return GamepadManager;
  64161. }());
  64162. BABYLON.GamepadManager = GamepadManager;
  64163. })(BABYLON || (BABYLON = {}));
  64164. //# sourceMappingURL=babylon.gamepadManager.js.map
  64165. var BABYLON;
  64166. (function (BABYLON) {
  64167. var StickValues = /** @class */ (function () {
  64168. function StickValues(x, y) {
  64169. this.x = x;
  64170. this.y = y;
  64171. }
  64172. return StickValues;
  64173. }());
  64174. BABYLON.StickValues = StickValues;
  64175. var Gamepad = /** @class */ (function () {
  64176. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64177. if (leftStickX === void 0) { leftStickX = 0; }
  64178. if (leftStickY === void 0) { leftStickY = 1; }
  64179. if (rightStickX === void 0) { rightStickX = 2; }
  64180. if (rightStickY === void 0) { rightStickY = 3; }
  64181. this.id = id;
  64182. this.index = index;
  64183. this.browserGamepad = browserGamepad;
  64184. this._isConnected = true;
  64185. this._invertLeftStickY = false;
  64186. this.type = Gamepad.GAMEPAD;
  64187. this._leftStickAxisX = leftStickX;
  64188. this._leftStickAxisY = leftStickY;
  64189. this._rightStickAxisX = rightStickX;
  64190. this._rightStickAxisY = rightStickY;
  64191. if (this.browserGamepad.axes.length >= 2) {
  64192. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64193. }
  64194. if (this.browserGamepad.axes.length >= 4) {
  64195. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64196. }
  64197. }
  64198. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64199. get: function () {
  64200. return this._isConnected;
  64201. },
  64202. enumerable: true,
  64203. configurable: true
  64204. });
  64205. Gamepad.prototype.onleftstickchanged = function (callback) {
  64206. this._onleftstickchanged = callback;
  64207. };
  64208. Gamepad.prototype.onrightstickchanged = function (callback) {
  64209. this._onrightstickchanged = callback;
  64210. };
  64211. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64212. get: function () {
  64213. return this._leftStick;
  64214. },
  64215. set: function (newValues) {
  64216. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64217. this._onleftstickchanged(newValues);
  64218. }
  64219. this._leftStick = newValues;
  64220. },
  64221. enumerable: true,
  64222. configurable: true
  64223. });
  64224. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64225. get: function () {
  64226. return this._rightStick;
  64227. },
  64228. set: function (newValues) {
  64229. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64230. this._onrightstickchanged(newValues);
  64231. }
  64232. this._rightStick = newValues;
  64233. },
  64234. enumerable: true,
  64235. configurable: true
  64236. });
  64237. Gamepad.prototype.update = function () {
  64238. if (this._leftStick) {
  64239. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64240. if (this._invertLeftStickY) {
  64241. this.leftStick.y *= -1;
  64242. }
  64243. }
  64244. if (this._rightStick) {
  64245. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64246. }
  64247. };
  64248. Gamepad.prototype.dispose = function () {
  64249. };
  64250. Gamepad.GAMEPAD = 0;
  64251. Gamepad.GENERIC = 1;
  64252. Gamepad.XBOX = 2;
  64253. Gamepad.POSE_ENABLED = 3;
  64254. return Gamepad;
  64255. }());
  64256. BABYLON.Gamepad = Gamepad;
  64257. var GenericPad = /** @class */ (function (_super) {
  64258. __extends(GenericPad, _super);
  64259. function GenericPad(id, index, browserGamepad) {
  64260. var _this = _super.call(this, id, index, browserGamepad) || this;
  64261. _this.onButtonDownObservable = new BABYLON.Observable();
  64262. _this.onButtonUpObservable = new BABYLON.Observable();
  64263. _this.type = Gamepad.GENERIC;
  64264. _this._buttons = new Array(browserGamepad.buttons.length);
  64265. return _this;
  64266. }
  64267. GenericPad.prototype.onbuttondown = function (callback) {
  64268. this._onbuttondown = callback;
  64269. };
  64270. GenericPad.prototype.onbuttonup = function (callback) {
  64271. this._onbuttonup = callback;
  64272. };
  64273. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64274. if (newValue !== currentValue) {
  64275. if (newValue === 1) {
  64276. if (this._onbuttondown) {
  64277. this._onbuttondown(buttonIndex);
  64278. }
  64279. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64280. }
  64281. if (newValue === 0) {
  64282. if (this._onbuttonup) {
  64283. this._onbuttonup(buttonIndex);
  64284. }
  64285. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64286. }
  64287. }
  64288. return newValue;
  64289. };
  64290. GenericPad.prototype.update = function () {
  64291. _super.prototype.update.call(this);
  64292. for (var index = 0; index < this._buttons.length; index++) {
  64293. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64294. }
  64295. };
  64296. GenericPad.prototype.dispose = function () {
  64297. _super.prototype.dispose.call(this);
  64298. this.onButtonDownObservable.clear();
  64299. this.onButtonUpObservable.clear();
  64300. };
  64301. return GenericPad;
  64302. }(Gamepad));
  64303. BABYLON.GenericPad = GenericPad;
  64304. })(BABYLON || (BABYLON = {}));
  64305. //# sourceMappingURL=babylon.gamepad.js.map
  64306. var BABYLON;
  64307. (function (BABYLON) {
  64308. var Xbox360Button;
  64309. (function (Xbox360Button) {
  64310. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64311. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64312. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64313. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64314. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64315. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64316. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64317. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64318. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64319. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64320. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64321. var Xbox360Dpad;
  64322. (function (Xbox360Dpad) {
  64323. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64324. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64325. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64326. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64327. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64328. var Xbox360Pad = /** @class */ (function (_super) {
  64329. __extends(Xbox360Pad, _super);
  64330. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64331. if (xboxOne === void 0) { xboxOne = false; }
  64332. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64333. _this._leftTrigger = 0;
  64334. _this._rightTrigger = 0;
  64335. _this.onButtonDownObservable = new BABYLON.Observable();
  64336. _this.onButtonUpObservable = new BABYLON.Observable();
  64337. _this.onPadDownObservable = new BABYLON.Observable();
  64338. _this.onPadUpObservable = new BABYLON.Observable();
  64339. _this._buttonA = 0;
  64340. _this._buttonB = 0;
  64341. _this._buttonX = 0;
  64342. _this._buttonY = 0;
  64343. _this._buttonBack = 0;
  64344. _this._buttonStart = 0;
  64345. _this._buttonLB = 0;
  64346. _this._buttonRB = 0;
  64347. _this._buttonLeftStick = 0;
  64348. _this._buttonRightStick = 0;
  64349. _this._dPadUp = 0;
  64350. _this._dPadDown = 0;
  64351. _this._dPadLeft = 0;
  64352. _this._dPadRight = 0;
  64353. _this._isXboxOnePad = false;
  64354. _this.type = BABYLON.Gamepad.XBOX;
  64355. _this._isXboxOnePad = xboxOne;
  64356. return _this;
  64357. }
  64358. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64359. this._onlefttriggerchanged = callback;
  64360. };
  64361. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64362. this._onrighttriggerchanged = callback;
  64363. };
  64364. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64365. get: function () {
  64366. return this._leftTrigger;
  64367. },
  64368. set: function (newValue) {
  64369. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64370. this._onlefttriggerchanged(newValue);
  64371. }
  64372. this._leftTrigger = newValue;
  64373. },
  64374. enumerable: true,
  64375. configurable: true
  64376. });
  64377. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64378. get: function () {
  64379. return this._rightTrigger;
  64380. },
  64381. set: function (newValue) {
  64382. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64383. this._onrighttriggerchanged(newValue);
  64384. }
  64385. this._rightTrigger = newValue;
  64386. },
  64387. enumerable: true,
  64388. configurable: true
  64389. });
  64390. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64391. this._onbuttondown = callback;
  64392. };
  64393. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64394. this._onbuttonup = callback;
  64395. };
  64396. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64397. this._ondpaddown = callback;
  64398. };
  64399. Xbox360Pad.prototype.ondpadup = function (callback) {
  64400. this._ondpadup = callback;
  64401. };
  64402. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64403. if (newValue !== currentValue) {
  64404. if (newValue === 1) {
  64405. if (this._onbuttondown) {
  64406. this._onbuttondown(buttonType);
  64407. }
  64408. this.onButtonDownObservable.notifyObservers(buttonType);
  64409. }
  64410. if (newValue === 0) {
  64411. if (this._onbuttonup) {
  64412. this._onbuttonup(buttonType);
  64413. }
  64414. this.onButtonUpObservable.notifyObservers(buttonType);
  64415. }
  64416. }
  64417. return newValue;
  64418. };
  64419. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64420. if (newValue !== currentValue) {
  64421. if (newValue === 1) {
  64422. if (this._ondpaddown) {
  64423. this._ondpaddown(buttonType);
  64424. }
  64425. this.onPadDownObservable.notifyObservers(buttonType);
  64426. }
  64427. if (newValue === 0) {
  64428. if (this._ondpadup) {
  64429. this._ondpadup(buttonType);
  64430. }
  64431. this.onPadUpObservable.notifyObservers(buttonType);
  64432. }
  64433. }
  64434. return newValue;
  64435. };
  64436. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64437. get: function () {
  64438. return this._buttonA;
  64439. },
  64440. set: function (value) {
  64441. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64447. get: function () {
  64448. return this._buttonB;
  64449. },
  64450. set: function (value) {
  64451. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64452. },
  64453. enumerable: true,
  64454. configurable: true
  64455. });
  64456. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64457. get: function () {
  64458. return this._buttonX;
  64459. },
  64460. set: function (value) {
  64461. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64462. },
  64463. enumerable: true,
  64464. configurable: true
  64465. });
  64466. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64467. get: function () {
  64468. return this._buttonY;
  64469. },
  64470. set: function (value) {
  64471. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64472. },
  64473. enumerable: true,
  64474. configurable: true
  64475. });
  64476. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64477. get: function () {
  64478. return this._buttonStart;
  64479. },
  64480. set: function (value) {
  64481. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64482. },
  64483. enumerable: true,
  64484. configurable: true
  64485. });
  64486. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64487. get: function () {
  64488. return this._buttonBack;
  64489. },
  64490. set: function (value) {
  64491. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64492. },
  64493. enumerable: true,
  64494. configurable: true
  64495. });
  64496. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64497. get: function () {
  64498. return this._buttonLB;
  64499. },
  64500. set: function (value) {
  64501. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64502. },
  64503. enumerable: true,
  64504. configurable: true
  64505. });
  64506. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64507. get: function () {
  64508. return this._buttonRB;
  64509. },
  64510. set: function (value) {
  64511. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64512. },
  64513. enumerable: true,
  64514. configurable: true
  64515. });
  64516. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64517. get: function () {
  64518. return this._buttonLeftStick;
  64519. },
  64520. set: function (value) {
  64521. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64522. },
  64523. enumerable: true,
  64524. configurable: true
  64525. });
  64526. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64527. get: function () {
  64528. return this._buttonRightStick;
  64529. },
  64530. set: function (value) {
  64531. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64532. },
  64533. enumerable: true,
  64534. configurable: true
  64535. });
  64536. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64537. get: function () {
  64538. return this._dPadUp;
  64539. },
  64540. set: function (value) {
  64541. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64542. },
  64543. enumerable: true,
  64544. configurable: true
  64545. });
  64546. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64547. get: function () {
  64548. return this._dPadDown;
  64549. },
  64550. set: function (value) {
  64551. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64552. },
  64553. enumerable: true,
  64554. configurable: true
  64555. });
  64556. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64557. get: function () {
  64558. return this._dPadLeft;
  64559. },
  64560. set: function (value) {
  64561. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64562. },
  64563. enumerable: true,
  64564. configurable: true
  64565. });
  64566. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64567. get: function () {
  64568. return this._dPadRight;
  64569. },
  64570. set: function (value) {
  64571. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64572. },
  64573. enumerable: true,
  64574. configurable: true
  64575. });
  64576. Xbox360Pad.prototype.update = function () {
  64577. _super.prototype.update.call(this);
  64578. if (this._isXboxOnePad) {
  64579. this.buttonA = this.browserGamepad.buttons[0].value;
  64580. this.buttonB = this.browserGamepad.buttons[1].value;
  64581. this.buttonX = this.browserGamepad.buttons[2].value;
  64582. this.buttonY = this.browserGamepad.buttons[3].value;
  64583. this.buttonLB = this.browserGamepad.buttons[4].value;
  64584. this.buttonRB = this.browserGamepad.buttons[5].value;
  64585. this.leftTrigger = this.browserGamepad.axes[2];
  64586. this.rightTrigger = this.browserGamepad.axes[5];
  64587. this.buttonBack = this.browserGamepad.buttons[9].value;
  64588. this.buttonStart = this.browserGamepad.buttons[8].value;
  64589. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64590. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64591. this.dPadUp = this.browserGamepad.buttons[11].value;
  64592. this.dPadDown = this.browserGamepad.buttons[12].value;
  64593. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64594. this.dPadRight = this.browserGamepad.buttons[14].value;
  64595. }
  64596. else {
  64597. this.buttonA = this.browserGamepad.buttons[0].value;
  64598. this.buttonB = this.browserGamepad.buttons[1].value;
  64599. this.buttonX = this.browserGamepad.buttons[2].value;
  64600. this.buttonY = this.browserGamepad.buttons[3].value;
  64601. this.buttonLB = this.browserGamepad.buttons[4].value;
  64602. this.buttonRB = this.browserGamepad.buttons[5].value;
  64603. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64604. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64605. this.buttonBack = this.browserGamepad.buttons[8].value;
  64606. this.buttonStart = this.browserGamepad.buttons[9].value;
  64607. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64608. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64609. this.dPadUp = this.browserGamepad.buttons[12].value;
  64610. this.dPadDown = this.browserGamepad.buttons[13].value;
  64611. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64612. this.dPadRight = this.browserGamepad.buttons[15].value;
  64613. }
  64614. };
  64615. Xbox360Pad.prototype.dispose = function () {
  64616. _super.prototype.dispose.call(this);
  64617. this.onButtonDownObservable.clear();
  64618. this.onButtonUpObservable.clear();
  64619. this.onPadDownObservable.clear();
  64620. this.onPadUpObservable.clear();
  64621. };
  64622. return Xbox360Pad;
  64623. }(BABYLON.Gamepad));
  64624. BABYLON.Xbox360Pad = Xbox360Pad;
  64625. })(BABYLON || (BABYLON = {}));
  64626. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64627. var BABYLON;
  64628. (function (BABYLON) {
  64629. var PoseEnabledControllerType;
  64630. (function (PoseEnabledControllerType) {
  64631. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64632. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64633. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64634. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64635. /**
  64636. * Google Daydream
  64637. */
  64638. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64639. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64640. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64641. var PoseEnabledControllerHelper = /** @class */ (function () {
  64642. function PoseEnabledControllerHelper() {
  64643. }
  64644. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64645. // Oculus Touch
  64646. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64647. return new BABYLON.OculusTouchController(vrGamepad);
  64648. }
  64649. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64650. return new BABYLON.WindowsMotionController(vrGamepad);
  64651. }
  64652. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64653. return new BABYLON.ViveController(vrGamepad);
  64654. }
  64655. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64656. return new BABYLON.GearVRController(vrGamepad);
  64657. }
  64658. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64659. return new BABYLON.DaydreamController(vrGamepad);
  64660. }
  64661. else {
  64662. return new BABYLON.GenericController(vrGamepad);
  64663. }
  64664. };
  64665. return PoseEnabledControllerHelper;
  64666. }());
  64667. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64668. var PoseEnabledController = /** @class */ (function (_super) {
  64669. __extends(PoseEnabledController, _super);
  64670. function PoseEnabledController(browserGamepad) {
  64671. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64672. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64673. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64674. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64675. // Represents device position and rotation in babylon space
  64676. _this.devicePosition = BABYLON.Vector3.Zero();
  64677. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64678. _this.deviceScaleFactor = 1;
  64679. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64680. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64681. /**
  64682. * Node to be used when casting a ray from the controller
  64683. */
  64684. _this._pointingPoseNode = null;
  64685. _this._workingMatrix = BABYLON.Matrix.Identity();
  64686. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64687. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64688. _this.position = BABYLON.Vector3.Zero();
  64689. _this.rotationQuaternion = new BABYLON.Quaternion();
  64690. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64691. _this._calculatedRotation = new BABYLON.Quaternion();
  64692. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64693. return _this;
  64694. }
  64695. PoseEnabledController.prototype.update = function () {
  64696. _super.prototype.update.call(this);
  64697. var pose = this.browserGamepad.pose;
  64698. this.updateFromDevice(pose);
  64699. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64700. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64701. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64702. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64703. if (this._mesh) {
  64704. this._mesh.position.copyFrom(this.devicePosition);
  64705. if (this._mesh.rotationQuaternion) {
  64706. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64707. }
  64708. }
  64709. };
  64710. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64711. if (poseData) {
  64712. this.rawPose = poseData;
  64713. if (poseData.position) {
  64714. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64715. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64716. this._deviceRoomPosition.z *= -1;
  64717. }
  64718. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64719. this._calculatedPosition.addInPlace(this.position);
  64720. }
  64721. var pose = this.rawPose;
  64722. if (poseData.orientation && pose.orientation) {
  64723. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64724. if (this._mesh) {
  64725. if (this._mesh.getScene().useRightHandedSystem) {
  64726. this._deviceRoomRotationQuaternion.z *= -1;
  64727. this._deviceRoomRotationQuaternion.w *= -1;
  64728. }
  64729. else {
  64730. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64731. }
  64732. }
  64733. // if the camera is set, rotate to the camera's rotation
  64734. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64735. }
  64736. }
  64737. };
  64738. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64739. if (this._mesh) {
  64740. this._mesh.parent = null;
  64741. }
  64742. this._mesh = mesh;
  64743. if (this._poseControlledCamera) {
  64744. this._mesh.parent = this._poseControlledCamera;
  64745. }
  64746. if (!this._mesh.rotationQuaternion) {
  64747. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64748. }
  64749. };
  64750. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64751. this._poseControlledCamera = camera;
  64752. if (this._mesh) {
  64753. this._mesh.parent = this._poseControlledCamera;
  64754. }
  64755. };
  64756. PoseEnabledController.prototype.dispose = function () {
  64757. if (this._mesh) {
  64758. this._mesh.dispose();
  64759. }
  64760. this._mesh = null;
  64761. _super.prototype.dispose.call(this);
  64762. };
  64763. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64764. get: function () {
  64765. return this._mesh;
  64766. },
  64767. enumerable: true,
  64768. configurable: true
  64769. });
  64770. PoseEnabledController.prototype.getForwardRay = function (length) {
  64771. if (length === void 0) { length = 100; }
  64772. if (!this.mesh) {
  64773. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64774. }
  64775. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64776. var origin = m.getTranslation();
  64777. var forward = new BABYLON.Vector3(0, 0, -1);
  64778. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64779. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64780. return new BABYLON.Ray(origin, direction, length);
  64781. };
  64782. /**
  64783. * Name of the child mesh that can be used to cast a ray from the controller
  64784. */
  64785. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64786. return PoseEnabledController;
  64787. }(BABYLON.Gamepad));
  64788. BABYLON.PoseEnabledController = PoseEnabledController;
  64789. })(BABYLON || (BABYLON = {}));
  64790. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64791. var BABYLON;
  64792. (function (BABYLON) {
  64793. var WebVRController = /** @class */ (function (_super) {
  64794. __extends(WebVRController, _super);
  64795. function WebVRController(vrGamepad) {
  64796. var _this = _super.call(this, vrGamepad) || this;
  64797. // Observables
  64798. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64799. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64800. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64801. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64802. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64803. _this.pad = { x: 0, y: 0 };
  64804. // avoid GC, store state in a tmp object
  64805. _this._changes = {
  64806. pressChanged: false,
  64807. touchChanged: false,
  64808. valueChanged: false,
  64809. changed: false
  64810. };
  64811. _this._buttons = new Array(vrGamepad.buttons.length);
  64812. _this.hand = vrGamepad.hand;
  64813. return _this;
  64814. }
  64815. WebVRController.prototype.onButtonStateChange = function (callback) {
  64816. this._onButtonStateChange = callback;
  64817. };
  64818. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64819. get: function () {
  64820. return this._defaultModel;
  64821. },
  64822. enumerable: true,
  64823. configurable: true
  64824. });
  64825. WebVRController.prototype.update = function () {
  64826. _super.prototype.update.call(this);
  64827. for (var index = 0; index < this._buttons.length; index++) {
  64828. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64829. }
  64830. ;
  64831. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64832. this.pad.x = this.leftStick.x;
  64833. this.pad.y = this.leftStick.y;
  64834. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64835. }
  64836. };
  64837. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64838. if (!newState) {
  64839. newState = {
  64840. pressed: false,
  64841. touched: false,
  64842. value: 0
  64843. };
  64844. }
  64845. if (!currentState) {
  64846. this._buttons[buttonIndex] = {
  64847. pressed: newState.pressed,
  64848. touched: newState.touched,
  64849. value: newState.value
  64850. };
  64851. return;
  64852. }
  64853. this._checkChanges(newState, currentState);
  64854. if (this._changes.changed) {
  64855. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64856. this._handleButtonChange(buttonIndex, newState, this._changes);
  64857. }
  64858. this._buttons[buttonIndex].pressed = newState.pressed;
  64859. this._buttons[buttonIndex].touched = newState.touched;
  64860. // oculus triggers are never 0, thou not touched.
  64861. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64862. };
  64863. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64864. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64865. this._changes.touchChanged = newState.touched !== currentState.touched;
  64866. this._changes.valueChanged = newState.value !== currentState.value;
  64867. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64868. return this._changes;
  64869. };
  64870. WebVRController.prototype.dispose = function () {
  64871. _super.prototype.dispose.call(this);
  64872. this.onTriggerStateChangedObservable.clear();
  64873. this.onMainButtonStateChangedObservable.clear();
  64874. this.onSecondaryButtonStateChangedObservable.clear();
  64875. this.onPadStateChangedObservable.clear();
  64876. this.onPadValuesChangedObservable.clear();
  64877. };
  64878. return WebVRController;
  64879. }(BABYLON.PoseEnabledController));
  64880. BABYLON.WebVRController = WebVRController;
  64881. })(BABYLON || (BABYLON = {}));
  64882. //# sourceMappingURL=babylon.webVRController.js.map
  64883. var BABYLON;
  64884. (function (BABYLON) {
  64885. var OculusTouchController = /** @class */ (function (_super) {
  64886. __extends(OculusTouchController, _super);
  64887. function OculusTouchController(vrGamepad) {
  64888. var _this = _super.call(this, vrGamepad) || this;
  64889. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64890. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64891. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64892. return _this;
  64893. }
  64894. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64895. var _this = this;
  64896. var meshName;
  64897. // Hand
  64898. if (this.hand === 'left') {
  64899. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64900. }
  64901. else {
  64902. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64903. }
  64904. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64905. /*
  64906. Parent Mesh name: oculus_touch_left
  64907. - body
  64908. - trigger
  64909. - thumbstick
  64910. - grip
  64911. - button_y
  64912. - button_x
  64913. - button_enter
  64914. */
  64915. _this._defaultModel = newMeshes[1];
  64916. _this.attachToMesh(_this._defaultModel);
  64917. if (meshLoaded) {
  64918. meshLoaded(_this._defaultModel);
  64919. }
  64920. });
  64921. };
  64922. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64923. // helper getters for left and right hand.
  64924. get: function () {
  64925. if (this.hand === 'right') {
  64926. return this.onMainButtonStateChangedObservable;
  64927. }
  64928. else {
  64929. throw new Error('No A button on left hand');
  64930. }
  64931. },
  64932. enumerable: true,
  64933. configurable: true
  64934. });
  64935. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64936. get: function () {
  64937. if (this.hand === 'right') {
  64938. return this.onSecondaryButtonStateChangedObservable;
  64939. }
  64940. else {
  64941. throw new Error('No B button on left hand');
  64942. }
  64943. },
  64944. enumerable: true,
  64945. configurable: true
  64946. });
  64947. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64948. get: function () {
  64949. if (this.hand === 'left') {
  64950. return this.onMainButtonStateChangedObservable;
  64951. }
  64952. else {
  64953. throw new Error('No X button on right hand');
  64954. }
  64955. },
  64956. enumerable: true,
  64957. configurable: true
  64958. });
  64959. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64960. get: function () {
  64961. if (this.hand === 'left') {
  64962. return this.onSecondaryButtonStateChangedObservable;
  64963. }
  64964. else {
  64965. throw new Error('No Y button on right hand');
  64966. }
  64967. },
  64968. enumerable: true,
  64969. configurable: true
  64970. });
  64971. /*
  64972. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64973. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64974. 2) secondary trigger (same)
  64975. 3) A (right) X (left), touch, pressed = value
  64976. 4) B / Y
  64977. 5) thumb rest
  64978. */
  64979. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64980. var notifyObject = state; //{ state: state, changes: changes };
  64981. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64982. switch (buttonIdx) {
  64983. case 0:
  64984. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64985. return;
  64986. case 1:// index trigger
  64987. if (this._defaultModel) {
  64988. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64989. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64990. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64991. }
  64992. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64993. return;
  64994. case 2:// secondary trigger
  64995. if (this._defaultModel) {
  64996. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64997. }
  64998. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64999. return;
  65000. case 3:
  65001. if (this._defaultModel) {
  65002. if (notifyObject.pressed) {
  65003. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65004. }
  65005. else {
  65006. (this._defaultModel.getChildren()[1]).position.y = 0;
  65007. }
  65008. }
  65009. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65010. return;
  65011. case 4:
  65012. if (this._defaultModel) {
  65013. if (notifyObject.pressed) {
  65014. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65015. }
  65016. else {
  65017. (this._defaultModel.getChildren()[2]).position.y = 0;
  65018. }
  65019. }
  65020. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65021. return;
  65022. case 5:
  65023. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65024. return;
  65025. }
  65026. };
  65027. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65028. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65029. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65030. return OculusTouchController;
  65031. }(BABYLON.WebVRController));
  65032. BABYLON.OculusTouchController = OculusTouchController;
  65033. })(BABYLON || (BABYLON = {}));
  65034. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65035. var BABYLON;
  65036. (function (BABYLON) {
  65037. var ViveController = /** @class */ (function (_super) {
  65038. __extends(ViveController, _super);
  65039. function ViveController(vrGamepad) {
  65040. var _this = _super.call(this, vrGamepad) || this;
  65041. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65042. _this._invertLeftStickY = true;
  65043. return _this;
  65044. }
  65045. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65046. var _this = this;
  65047. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65048. /*
  65049. Parent Mesh name: ViveWand
  65050. - body
  65051. - r_gripper
  65052. - l_gripper
  65053. - menu_button
  65054. - system_button
  65055. - trackpad
  65056. - trigger
  65057. - LED
  65058. */
  65059. _this._defaultModel = newMeshes[1];
  65060. _this.attachToMesh(_this._defaultModel);
  65061. if (meshLoaded) {
  65062. meshLoaded(_this._defaultModel);
  65063. }
  65064. });
  65065. };
  65066. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65067. get: function () {
  65068. return this.onMainButtonStateChangedObservable;
  65069. },
  65070. enumerable: true,
  65071. configurable: true
  65072. });
  65073. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65074. get: function () {
  65075. return this.onMainButtonStateChangedObservable;
  65076. },
  65077. enumerable: true,
  65078. configurable: true
  65079. });
  65080. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65081. get: function () {
  65082. return this.onSecondaryButtonStateChangedObservable;
  65083. },
  65084. enumerable: true,
  65085. configurable: true
  65086. });
  65087. /**
  65088. * Vive mapping:
  65089. * 0: touchpad
  65090. * 1: trigger
  65091. * 2: left AND right buttons
  65092. * 3: menu button
  65093. */
  65094. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65095. var notifyObject = state; //{ state: state, changes: changes };
  65096. switch (buttonIdx) {
  65097. case 0:
  65098. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65099. return;
  65100. case 1:// index trigger
  65101. if (this._defaultModel) {
  65102. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65103. }
  65104. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65105. return;
  65106. case 2:// left AND right button
  65107. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65108. return;
  65109. case 3:
  65110. if (this._defaultModel) {
  65111. if (notifyObject.pressed) {
  65112. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65113. }
  65114. else {
  65115. (this._defaultModel.getChildren()[2]).position.y = 0;
  65116. }
  65117. }
  65118. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65119. return;
  65120. }
  65121. };
  65122. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65123. ViveController.MODEL_FILENAME = 'wand.babylon';
  65124. return ViveController;
  65125. }(BABYLON.WebVRController));
  65126. BABYLON.ViveController = ViveController;
  65127. })(BABYLON || (BABYLON = {}));
  65128. //# sourceMappingURL=babylon.viveController.js.map
  65129. var BABYLON;
  65130. (function (BABYLON) {
  65131. var GenericController = /** @class */ (function (_super) {
  65132. __extends(GenericController, _super);
  65133. function GenericController(vrGamepad) {
  65134. return _super.call(this, vrGamepad) || this;
  65135. }
  65136. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65137. var _this = this;
  65138. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65139. _this._defaultModel = newMeshes[1];
  65140. _this.attachToMesh(_this._defaultModel);
  65141. if (meshLoaded) {
  65142. meshLoaded(_this._defaultModel);
  65143. }
  65144. });
  65145. };
  65146. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65147. console.log("Button id: " + buttonIdx + "state: ");
  65148. console.dir(state);
  65149. };
  65150. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65151. GenericController.MODEL_FILENAME = 'generic.babylon';
  65152. return GenericController;
  65153. }(BABYLON.WebVRController));
  65154. BABYLON.GenericController = GenericController;
  65155. })(BABYLON || (BABYLON = {}));
  65156. //# sourceMappingURL=babylon.genericController.js.map
  65157. var BABYLON;
  65158. (function (BABYLON) {
  65159. var LoadedMeshInfo = /** @class */ (function () {
  65160. function LoadedMeshInfo() {
  65161. this.buttonMeshes = {};
  65162. this.axisMeshes = {};
  65163. }
  65164. return LoadedMeshInfo;
  65165. }());
  65166. var WindowsMotionController = /** @class */ (function (_super) {
  65167. __extends(WindowsMotionController, _super);
  65168. function WindowsMotionController(vrGamepad) {
  65169. var _this = _super.call(this, vrGamepad) || this;
  65170. _this._mapping = {
  65171. // Semantic button names
  65172. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65173. // A mapping of the button name to glTF model node name
  65174. // that should be transformed by button value.
  65175. buttonMeshNames: {
  65176. 'trigger': 'SELECT',
  65177. 'menu': 'MENU',
  65178. 'grip': 'GRASP',
  65179. 'thumbstick': 'THUMBSTICK_PRESS',
  65180. 'trackpad': 'TOUCHPAD_PRESS'
  65181. },
  65182. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65183. buttonObservableNames: {
  65184. 'trigger': 'onTriggerStateChangedObservable',
  65185. 'menu': 'onSecondaryButtonStateChangedObservable',
  65186. 'grip': 'onMainButtonStateChangedObservable',
  65187. 'thumbstick': 'onPadStateChangedObservable',
  65188. 'trackpad': 'onTrackpadChangedObservable'
  65189. },
  65190. // A mapping of the axis name to glTF model node name
  65191. // that should be transformed by axis value.
  65192. // This array mirrors the browserGamepad.axes array, such that
  65193. // the mesh corresponding to axis 0 is in this array index 0.
  65194. axisMeshNames: [
  65195. 'THUMBSTICK_X',
  65196. 'THUMBSTICK_Y',
  65197. 'TOUCHPAD_TOUCH_X',
  65198. 'TOUCHPAD_TOUCH_Y'
  65199. ],
  65200. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65201. };
  65202. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65203. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65204. _this.trackpad = { x: 0, y: 0 };
  65205. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65206. _this._loadedMeshInfo = null;
  65207. return _this;
  65208. }
  65209. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65210. get: function () {
  65211. return this.onTriggerStateChangedObservable;
  65212. },
  65213. enumerable: true,
  65214. configurable: true
  65215. });
  65216. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65217. get: function () {
  65218. return this.onSecondaryButtonStateChangedObservable;
  65219. },
  65220. enumerable: true,
  65221. configurable: true
  65222. });
  65223. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65224. get: function () {
  65225. return this.onMainButtonStateChangedObservable;
  65226. },
  65227. enumerable: true,
  65228. configurable: true
  65229. });
  65230. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65231. get: function () {
  65232. return this.onPadStateChangedObservable;
  65233. },
  65234. enumerable: true,
  65235. configurable: true
  65236. });
  65237. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65238. get: function () {
  65239. return this.onTrackpadChangedObservable;
  65240. },
  65241. enumerable: true,
  65242. configurable: true
  65243. });
  65244. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65245. get: function () {
  65246. return this.onTrackpadValuesChangedObservable;
  65247. },
  65248. enumerable: true,
  65249. configurable: true
  65250. });
  65251. /**
  65252. * Called once per frame by the engine.
  65253. */
  65254. WindowsMotionController.prototype.update = function () {
  65255. _super.prototype.update.call(this);
  65256. if (this.browserGamepad.axes) {
  65257. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65258. this.trackpad.x = this.browserGamepad["axes"][2];
  65259. this.trackpad.y = this.browserGamepad["axes"][3];
  65260. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65261. }
  65262. // Only need to animate axes if there is a loaded mesh
  65263. if (this._loadedMeshInfo) {
  65264. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65265. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65266. }
  65267. }
  65268. }
  65269. };
  65270. /**
  65271. * Called once for each button that changed state since the last frame
  65272. * @param buttonIdx Which button index changed
  65273. * @param state New state of the button
  65274. * @param changes Which properties on the state changed since last frame
  65275. */
  65276. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65277. var buttonName = this._mapping.buttons[buttonIdx];
  65278. if (!buttonName) {
  65279. return;
  65280. }
  65281. // Only emit events for buttons that we know how to map from index to name
  65282. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65283. if (observable) {
  65284. observable.notifyObservers(state);
  65285. }
  65286. this.lerpButtonTransform(buttonName, state.value);
  65287. };
  65288. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65289. // If there is no loaded mesh, there is nothing to transform.
  65290. if (!this._loadedMeshInfo) {
  65291. return;
  65292. }
  65293. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65294. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65295. return;
  65296. }
  65297. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65298. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65299. };
  65300. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65301. if (!this._loadedMeshInfo) {
  65302. return;
  65303. }
  65304. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65305. if (!meshInfo) {
  65306. return;
  65307. }
  65308. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65309. return;
  65310. }
  65311. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65312. var lerpValue = axisValue * 0.5 + 0.5;
  65313. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65314. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65315. };
  65316. /**
  65317. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65318. * @param scene scene in which to add meshes
  65319. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65320. */
  65321. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65322. var _this = this;
  65323. if (forceDefault === void 0) { forceDefault = false; }
  65324. var path;
  65325. var filename;
  65326. // Checking if GLB loader is present
  65327. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65328. // Determine the device specific folder based on the ID suffix
  65329. var device = 'default';
  65330. if (this.id && !forceDefault) {
  65331. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65332. device = ((match && match[0]) || device);
  65333. }
  65334. // Hand
  65335. if (this.hand === 'left') {
  65336. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65337. }
  65338. else {
  65339. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65340. }
  65341. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65342. }
  65343. else {
  65344. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65345. path = BABYLON.GenericController.MODEL_BASE_URL;
  65346. filename = BABYLON.GenericController.MODEL_FILENAME;
  65347. }
  65348. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65349. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65350. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65351. if (!_this._loadedMeshInfo) {
  65352. return;
  65353. }
  65354. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65355. _this.attachToMesh(_this._defaultModel);
  65356. if (meshLoaded) {
  65357. meshLoaded(_this._defaultModel);
  65358. }
  65359. }, null, function (scene, message) {
  65360. BABYLON.Tools.Log(message);
  65361. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65362. if (!forceDefault) {
  65363. _this.initControllerMesh(scene, meshLoaded, true);
  65364. }
  65365. });
  65366. };
  65367. /**
  65368. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65369. * can be transformed by button presses and axes values, based on this._mapping.
  65370. *
  65371. * @param scene scene in which the meshes exist
  65372. * @param meshes list of meshes that make up the controller model to process
  65373. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65374. */
  65375. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65376. var loadedMeshInfo = null;
  65377. // Create a new mesh to contain the glTF hierarchy
  65378. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65379. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65380. var childMesh = null;
  65381. for (var i = 0; i < meshes.length; i++) {
  65382. var mesh = meshes[i];
  65383. if (!mesh.parent) {
  65384. // Exclude controller meshes from picking results
  65385. mesh.isPickable = false;
  65386. // Handle root node, attach to the new parentMesh
  65387. childMesh = mesh;
  65388. break;
  65389. }
  65390. }
  65391. if (childMesh) {
  65392. childMesh.setParent(parentMesh);
  65393. // Create our mesh info. Note that this method will always return non-null.
  65394. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65395. }
  65396. else {
  65397. BABYLON.Tools.Warn('Could not find root node in model file.');
  65398. }
  65399. return loadedMeshInfo;
  65400. };
  65401. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65402. var loadedMeshInfo = new LoadedMeshInfo();
  65403. var i;
  65404. loadedMeshInfo.rootNode = rootNode;
  65405. // Reset the caches
  65406. loadedMeshInfo.buttonMeshes = {};
  65407. loadedMeshInfo.axisMeshes = {};
  65408. // Button Meshes
  65409. for (i = 0; i < this._mapping.buttons.length; i++) {
  65410. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65411. if (!buttonMeshName) {
  65412. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65413. continue;
  65414. }
  65415. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65416. if (!buttonMesh) {
  65417. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65418. continue;
  65419. }
  65420. var buttonMeshInfo = {
  65421. index: i,
  65422. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65423. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65424. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65425. };
  65426. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65427. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65428. }
  65429. else {
  65430. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65431. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65432. '(VALUE: ' + !!buttonMeshInfo.value +
  65433. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65434. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65435. ')');
  65436. }
  65437. }
  65438. // Axis Meshes
  65439. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65440. var axisMeshName = this._mapping.axisMeshNames[i];
  65441. if (!axisMeshName) {
  65442. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65443. continue;
  65444. }
  65445. var axisMesh = getChildByName(rootNode, axisMeshName);
  65446. if (!axisMesh) {
  65447. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65448. continue;
  65449. }
  65450. var axisMeshInfo = {
  65451. index: i,
  65452. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65453. min: getImmediateChildByName(axisMesh, 'MIN'),
  65454. max: getImmediateChildByName(axisMesh, 'MAX')
  65455. };
  65456. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65457. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65458. }
  65459. else {
  65460. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65461. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65462. '(VALUE: ' + !!axisMeshInfo.value +
  65463. ', MIN: ' + !!axisMeshInfo.min +
  65464. ', MAX:' + !!axisMeshInfo.max +
  65465. ')');
  65466. }
  65467. }
  65468. // Pointing Ray
  65469. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65470. if (!loadedMeshInfo.pointingPoseNode) {
  65471. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65472. }
  65473. return loadedMeshInfo;
  65474. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65475. function getChildByName(node, name) {
  65476. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65477. }
  65478. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65479. function getImmediateChildByName(node, name) {
  65480. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65481. }
  65482. };
  65483. WindowsMotionController.prototype.getForwardRay = function (length) {
  65484. if (length === void 0) { length = 100; }
  65485. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65486. return _super.prototype.getForwardRay.call(this, length);
  65487. }
  65488. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65489. var origin = m.getTranslation();
  65490. var forward = new BABYLON.Vector3(0, 0, -1);
  65491. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65492. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65493. return new BABYLON.Ray(origin, direction, length);
  65494. };
  65495. WindowsMotionController.prototype.dispose = function () {
  65496. _super.prototype.dispose.call(this);
  65497. this.onTrackpadChangedObservable.clear();
  65498. };
  65499. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65500. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65501. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65502. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65503. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65504. return WindowsMotionController;
  65505. }(BABYLON.WebVRController));
  65506. BABYLON.WindowsMotionController = WindowsMotionController;
  65507. })(BABYLON || (BABYLON = {}));
  65508. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65509. var BABYLON;
  65510. (function (BABYLON) {
  65511. var GearVRController = /** @class */ (function (_super) {
  65512. __extends(GearVRController, _super);
  65513. function GearVRController(vrGamepad) {
  65514. var _this = _super.call(this, vrGamepad) || this;
  65515. _this._buttonIndexToObservableNameMap = [
  65516. 'onTrackpadChangedObservable',
  65517. 'onTriggerStateChangedObservable' // Trigger
  65518. ];
  65519. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65520. return _this;
  65521. }
  65522. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65523. var _this = this;
  65524. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65525. _this._defaultModel = newMeshes[1];
  65526. _this.attachToMesh(_this._defaultModel);
  65527. if (meshLoaded) {
  65528. meshLoaded(_this._defaultModel);
  65529. }
  65530. });
  65531. };
  65532. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65533. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65534. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65535. // Only emit events for buttons that we know how to map from index to observable
  65536. var observable = this[observableName];
  65537. if (observable) {
  65538. observable.notifyObservers(state);
  65539. }
  65540. }
  65541. };
  65542. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65543. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65544. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65545. return GearVRController;
  65546. }(BABYLON.WebVRController));
  65547. BABYLON.GearVRController = GearVRController;
  65548. })(BABYLON || (BABYLON = {}));
  65549. //# sourceMappingURL=babylon.gearVRController.js.map
  65550. var BABYLON;
  65551. (function (BABYLON) {
  65552. /**
  65553. * Google Daydream controller
  65554. */
  65555. var DaydreamController = /** @class */ (function (_super) {
  65556. __extends(DaydreamController, _super);
  65557. function DaydreamController(vrGamepad) {
  65558. var _this = _super.call(this, vrGamepad) || this;
  65559. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65560. return _this;
  65561. }
  65562. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65563. var _this = this;
  65564. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65565. _this._defaultModel = newMeshes[1];
  65566. _this.attachToMesh(_this._defaultModel);
  65567. if (meshLoaded) {
  65568. meshLoaded(_this._defaultModel);
  65569. }
  65570. });
  65571. };
  65572. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65573. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65574. if (buttonIdx === 0) {
  65575. var observable = this.onTriggerStateChangedObservable;
  65576. if (observable) {
  65577. observable.notifyObservers(state);
  65578. }
  65579. }
  65580. else {
  65581. // If the app or home buttons are ever made available
  65582. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65583. }
  65584. };
  65585. /**
  65586. * Base Url for the controller model.
  65587. */
  65588. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65589. /**
  65590. * File name for the controller model.
  65591. */
  65592. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65593. /**
  65594. * Gamepad Id prefix used to identify Daydream Controller.
  65595. */
  65596. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65597. return DaydreamController;
  65598. }(BABYLON.WebVRController));
  65599. BABYLON.DaydreamController = DaydreamController;
  65600. })(BABYLON || (BABYLON = {}));
  65601. //# sourceMappingURL=babylon.daydreamController.js.map
  65602. var BABYLON;
  65603. (function (BABYLON) {
  65604. var FollowCamera = /** @class */ (function (_super) {
  65605. __extends(FollowCamera, _super);
  65606. function FollowCamera(name, position, scene, lockedTarget) {
  65607. if (lockedTarget === void 0) { lockedTarget = null; }
  65608. var _this = _super.call(this, name, position, scene) || this;
  65609. _this.radius = 12;
  65610. _this.rotationOffset = 0;
  65611. _this.heightOffset = 4;
  65612. _this.cameraAcceleration = 0.05;
  65613. _this.maxCameraSpeed = 20;
  65614. _this.lockedTarget = lockedTarget;
  65615. return _this;
  65616. }
  65617. FollowCamera.prototype.getRadians = function (degrees) {
  65618. return degrees * Math.PI / 180;
  65619. };
  65620. FollowCamera.prototype.follow = function (cameraTarget) {
  65621. if (!cameraTarget)
  65622. return;
  65623. var yRotation;
  65624. if (cameraTarget.rotationQuaternion) {
  65625. var rotMatrix = new BABYLON.Matrix();
  65626. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65627. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65628. }
  65629. else {
  65630. yRotation = cameraTarget.rotation.y;
  65631. }
  65632. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65633. var targetPosition = cameraTarget.getAbsolutePosition();
  65634. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65635. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65636. var dx = targetX - this.position.x;
  65637. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65638. var dz = (targetZ) - this.position.z;
  65639. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65640. var vy = dy * this.cameraAcceleration;
  65641. var vz = dz * this.cameraAcceleration * 2;
  65642. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65643. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65644. }
  65645. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65646. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65647. }
  65648. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65649. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65650. }
  65651. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65652. this.setTarget(targetPosition);
  65653. };
  65654. FollowCamera.prototype._checkInputs = function () {
  65655. _super.prototype._checkInputs.call(this);
  65656. if (this.lockedTarget) {
  65657. this.follow(this.lockedTarget);
  65658. }
  65659. };
  65660. FollowCamera.prototype.getClassName = function () {
  65661. return "FollowCamera";
  65662. };
  65663. __decorate([
  65664. BABYLON.serialize()
  65665. ], FollowCamera.prototype, "radius", void 0);
  65666. __decorate([
  65667. BABYLON.serialize()
  65668. ], FollowCamera.prototype, "rotationOffset", void 0);
  65669. __decorate([
  65670. BABYLON.serialize()
  65671. ], FollowCamera.prototype, "heightOffset", void 0);
  65672. __decorate([
  65673. BABYLON.serialize()
  65674. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65675. __decorate([
  65676. BABYLON.serialize()
  65677. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65678. __decorate([
  65679. BABYLON.serializeAsMeshReference("lockedTargetId")
  65680. ], FollowCamera.prototype, "lockedTarget", void 0);
  65681. return FollowCamera;
  65682. }(BABYLON.TargetCamera));
  65683. BABYLON.FollowCamera = FollowCamera;
  65684. var ArcFollowCamera = /** @class */ (function (_super) {
  65685. __extends(ArcFollowCamera, _super);
  65686. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65687. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65688. _this.alpha = alpha;
  65689. _this.beta = beta;
  65690. _this.radius = radius;
  65691. _this.target = target;
  65692. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65693. _this.follow();
  65694. return _this;
  65695. }
  65696. ArcFollowCamera.prototype.follow = function () {
  65697. if (!this.target) {
  65698. return;
  65699. }
  65700. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65701. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65702. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65703. var targetPosition = this.target.getAbsolutePosition();
  65704. this.position = targetPosition.add(this._cartesianCoordinates);
  65705. this.setTarget(targetPosition);
  65706. };
  65707. ArcFollowCamera.prototype._checkInputs = function () {
  65708. _super.prototype._checkInputs.call(this);
  65709. this.follow();
  65710. };
  65711. ArcFollowCamera.prototype.getClassName = function () {
  65712. return "ArcFollowCamera";
  65713. };
  65714. return ArcFollowCamera;
  65715. }(BABYLON.TargetCamera));
  65716. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65717. })(BABYLON || (BABYLON = {}));
  65718. //# sourceMappingURL=babylon.followCamera.js.map
  65719. var BABYLON;
  65720. (function (BABYLON) {
  65721. // We're mainly based on the logic defined into the FreeCamera code
  65722. var UniversalCamera = /** @class */ (function (_super) {
  65723. __extends(UniversalCamera, _super);
  65724. //-- end properties for backward compatibility for inputs
  65725. function UniversalCamera(name, position, scene) {
  65726. var _this = _super.call(this, name, position, scene) || this;
  65727. _this.inputs.addGamepad();
  65728. return _this;
  65729. }
  65730. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65731. //-- Begin properties for backward compatibility for inputs
  65732. get: function () {
  65733. var gamepad = this.inputs.attached["gamepad"];
  65734. if (gamepad)
  65735. return gamepad.gamepadAngularSensibility;
  65736. return 0;
  65737. },
  65738. set: function (value) {
  65739. var gamepad = this.inputs.attached["gamepad"];
  65740. if (gamepad)
  65741. gamepad.gamepadAngularSensibility = value;
  65742. },
  65743. enumerable: true,
  65744. configurable: true
  65745. });
  65746. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65747. get: function () {
  65748. var gamepad = this.inputs.attached["gamepad"];
  65749. if (gamepad)
  65750. return gamepad.gamepadMoveSensibility;
  65751. return 0;
  65752. },
  65753. set: function (value) {
  65754. var gamepad = this.inputs.attached["gamepad"];
  65755. if (gamepad)
  65756. gamepad.gamepadMoveSensibility = value;
  65757. },
  65758. enumerable: true,
  65759. configurable: true
  65760. });
  65761. UniversalCamera.prototype.getClassName = function () {
  65762. return "UniversalCamera";
  65763. };
  65764. return UniversalCamera;
  65765. }(BABYLON.TouchCamera));
  65766. BABYLON.UniversalCamera = UniversalCamera;
  65767. })(BABYLON || (BABYLON = {}));
  65768. //# sourceMappingURL=babylon.universalCamera.js.map
  65769. var BABYLON;
  65770. (function (BABYLON) {
  65771. // We're mainly based on the logic defined into the FreeCamera code
  65772. var GamepadCamera = /** @class */ (function (_super) {
  65773. __extends(GamepadCamera, _super);
  65774. //-- end properties for backward compatibility for inputs
  65775. function GamepadCamera(name, position, scene) {
  65776. return _super.call(this, name, position, scene) || this;
  65777. }
  65778. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65779. //-- Begin properties for backward compatibility for inputs
  65780. get: function () {
  65781. var gamepad = this.inputs.attached["gamepad"];
  65782. if (gamepad)
  65783. return gamepad.gamepadAngularSensibility;
  65784. return 0;
  65785. },
  65786. set: function (value) {
  65787. var gamepad = this.inputs.attached["gamepad"];
  65788. if (gamepad)
  65789. gamepad.gamepadAngularSensibility = value;
  65790. },
  65791. enumerable: true,
  65792. configurable: true
  65793. });
  65794. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65795. get: function () {
  65796. var gamepad = this.inputs.attached["gamepad"];
  65797. if (gamepad)
  65798. return gamepad.gamepadMoveSensibility;
  65799. return 0;
  65800. },
  65801. set: function (value) {
  65802. var gamepad = this.inputs.attached["gamepad"];
  65803. if (gamepad)
  65804. gamepad.gamepadMoveSensibility = value;
  65805. },
  65806. enumerable: true,
  65807. configurable: true
  65808. });
  65809. GamepadCamera.prototype.getClassName = function () {
  65810. return "GamepadCamera";
  65811. };
  65812. return GamepadCamera;
  65813. }(BABYLON.UniversalCamera));
  65814. BABYLON.GamepadCamera = GamepadCamera;
  65815. })(BABYLON || (BABYLON = {}));
  65816. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65817. var BABYLON;
  65818. (function (BABYLON) {
  65819. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65820. function PostProcessRenderPipelineManager() {
  65821. this._renderPipelines = {};
  65822. }
  65823. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65824. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65825. };
  65826. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65827. if (unique === void 0) { unique = false; }
  65828. var renderPipeline = this._renderPipelines[renderPipelineName];
  65829. if (!renderPipeline) {
  65830. return;
  65831. }
  65832. renderPipeline._attachCameras(cameras, unique);
  65833. };
  65834. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65835. var renderPipeline = this._renderPipelines[renderPipelineName];
  65836. if (!renderPipeline) {
  65837. return;
  65838. }
  65839. renderPipeline._detachCameras(cameras);
  65840. };
  65841. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65842. var renderPipeline = this._renderPipelines[renderPipelineName];
  65843. if (!renderPipeline) {
  65844. return;
  65845. }
  65846. renderPipeline._enableEffect(renderEffectName, cameras);
  65847. };
  65848. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65849. var renderPipeline = this._renderPipelines[renderPipelineName];
  65850. if (!renderPipeline) {
  65851. return;
  65852. }
  65853. renderPipeline._disableEffect(renderEffectName, cameras);
  65854. };
  65855. PostProcessRenderPipelineManager.prototype.update = function () {
  65856. for (var renderPipelineName in this._renderPipelines) {
  65857. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65858. var pipeline = this._renderPipelines[renderPipelineName];
  65859. if (!pipeline.isSupported) {
  65860. pipeline.dispose();
  65861. delete this._renderPipelines[renderPipelineName];
  65862. }
  65863. else {
  65864. pipeline._update();
  65865. }
  65866. }
  65867. }
  65868. };
  65869. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65870. for (var renderPipelineName in this._renderPipelines) {
  65871. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65872. var pipeline = this._renderPipelines[renderPipelineName];
  65873. pipeline._rebuild();
  65874. }
  65875. }
  65876. };
  65877. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65878. for (var renderPipelineName in this._renderPipelines) {
  65879. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65880. var pipeline = this._renderPipelines[renderPipelineName];
  65881. pipeline.dispose();
  65882. }
  65883. }
  65884. };
  65885. return PostProcessRenderPipelineManager;
  65886. }());
  65887. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65888. })(BABYLON || (BABYLON = {}));
  65889. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65890. var BABYLON;
  65891. (function (BABYLON) {
  65892. /**
  65893. * This represents a set of one or more post processes in Babylon.
  65894. * A post process can be used to apply a shader to a texture after it is rendered.
  65895. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65896. */
  65897. var PostProcessRenderEffect = /** @class */ (function () {
  65898. /**
  65899. * Instantiates a post process render effect.
  65900. * A post process can be used to apply a shader to a texture after it is rendered.
  65901. * @param engine The engine the effect is tied to
  65902. * @param name The name of the effect
  65903. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65904. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65905. */
  65906. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65907. this._name = name;
  65908. this._singleInstance = singleInstance || true;
  65909. this._getPostProcesses = getPostProcesses;
  65910. this._cameras = {};
  65911. this._indicesForCamera = {};
  65912. this._postProcesses = {};
  65913. }
  65914. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65915. /**
  65916. * Checks if all the post processes in the effect are supported.
  65917. */
  65918. get: function () {
  65919. for (var index in this._postProcesses) {
  65920. for (var ppIndex in this._postProcesses[index]) {
  65921. if (!this._postProcesses[index][ppIndex].isSupported) {
  65922. return false;
  65923. }
  65924. }
  65925. }
  65926. return true;
  65927. },
  65928. enumerable: true,
  65929. configurable: true
  65930. });
  65931. /**
  65932. * Updates the current state of the effect
  65933. */
  65934. PostProcessRenderEffect.prototype._update = function () {
  65935. };
  65936. /**
  65937. * Attaches the effect on cameras
  65938. * @param cameras The camera to attach to.
  65939. */
  65940. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65941. var _this = this;
  65942. var cameraKey;
  65943. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65944. if (!cams) {
  65945. return;
  65946. }
  65947. for (var i = 0; i < cams.length; i++) {
  65948. var camera = cams[i];
  65949. var cameraName = camera.name;
  65950. if (this._singleInstance) {
  65951. cameraKey = 0;
  65952. }
  65953. else {
  65954. cameraKey = cameraName;
  65955. }
  65956. if (!this._postProcesses[cameraKey]) {
  65957. var postProcess = this._getPostProcesses();
  65958. if (postProcess) {
  65959. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65960. }
  65961. }
  65962. if (!this._indicesForCamera[cameraName]) {
  65963. this._indicesForCamera[cameraName] = [];
  65964. }
  65965. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65966. var index = camera.attachPostProcess(postProcess);
  65967. _this._indicesForCamera[cameraName].push(index);
  65968. });
  65969. if (!this._cameras[cameraName]) {
  65970. this._cameras[cameraName] = camera;
  65971. }
  65972. }
  65973. };
  65974. /**
  65975. * Detatches the effect on cameras
  65976. * @param cameras The camera to detatch from.
  65977. */
  65978. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65979. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65980. if (!cams) {
  65981. return;
  65982. }
  65983. for (var i = 0; i < cams.length; i++) {
  65984. var camera = cams[i];
  65985. var cameraName = camera.name;
  65986. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65987. camera.detachPostProcess(postProcess);
  65988. });
  65989. if (this._cameras[cameraName]) {
  65990. //this._indicesForCamera.splice(index, 1);
  65991. this._cameras[cameraName] = null;
  65992. }
  65993. }
  65994. };
  65995. /**
  65996. * Enables the effect on given cameras
  65997. * @param cameras The camera to enable.
  65998. */
  65999. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66000. var _this = this;
  66001. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66002. if (!cams) {
  66003. return;
  66004. }
  66005. for (var i = 0; i < cams.length; i++) {
  66006. var camera = cams[i];
  66007. var cameraName = camera.name;
  66008. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66009. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66010. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66011. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66012. });
  66013. }
  66014. }
  66015. }
  66016. };
  66017. /**
  66018. * Disables the effect on the given cameras
  66019. * @param cameras The camera to disable.
  66020. */
  66021. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66022. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66023. if (!cams) {
  66024. return;
  66025. }
  66026. for (var i = 0; i < cams.length; i++) {
  66027. var camera = cams[i];
  66028. var cameraName = camera.name;
  66029. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66030. camera.detachPostProcess(postProcess);
  66031. });
  66032. }
  66033. };
  66034. /**
  66035. * Gets a list of the post processes contained in the effect.
  66036. * @param camera The camera to get the post processes on.
  66037. * @returns The list of the post processes in the effect.
  66038. */
  66039. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66040. if (this._singleInstance) {
  66041. return this._postProcesses[0];
  66042. }
  66043. else {
  66044. if (!camera) {
  66045. return null;
  66046. }
  66047. return this._postProcesses[camera.name];
  66048. }
  66049. };
  66050. return PostProcessRenderEffect;
  66051. }());
  66052. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66053. })(BABYLON || (BABYLON = {}));
  66054. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66055. var BABYLON;
  66056. (function (BABYLON) {
  66057. var PostProcessRenderPipeline = /** @class */ (function () {
  66058. function PostProcessRenderPipeline(engine, name) {
  66059. this.engine = engine;
  66060. this._name = name;
  66061. this._renderEffects = {};
  66062. this._renderEffectsForIsolatedPass = new Array();
  66063. this._cameras = [];
  66064. }
  66065. PostProcessRenderPipeline.prototype.getClassName = function () {
  66066. return "PostProcessRenderPipeline";
  66067. };
  66068. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66069. get: function () {
  66070. for (var renderEffectName in this._renderEffects) {
  66071. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66072. if (!this._renderEffects[renderEffectName].isSupported) {
  66073. return false;
  66074. }
  66075. }
  66076. }
  66077. return true;
  66078. },
  66079. enumerable: true,
  66080. configurable: true
  66081. });
  66082. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66083. this._renderEffects[renderEffect._name] = renderEffect;
  66084. };
  66085. // private
  66086. PostProcessRenderPipeline.prototype._rebuild = function () {
  66087. };
  66088. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66089. var renderEffects = this._renderEffects[renderEffectName];
  66090. if (!renderEffects) {
  66091. return;
  66092. }
  66093. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66094. };
  66095. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66096. var renderEffects = this._renderEffects[renderEffectName];
  66097. if (!renderEffects) {
  66098. return;
  66099. }
  66100. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66101. };
  66102. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66103. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66104. if (!cams) {
  66105. return;
  66106. }
  66107. var indicesToDelete = [];
  66108. var i;
  66109. for (i = 0; i < cams.length; i++) {
  66110. var camera = cams[i];
  66111. var cameraName = camera.name;
  66112. if (this._cameras.indexOf(camera) === -1) {
  66113. this._cameras[cameraName] = camera;
  66114. }
  66115. else if (unique) {
  66116. indicesToDelete.push(i);
  66117. }
  66118. }
  66119. for (i = 0; i < indicesToDelete.length; i++) {
  66120. cameras.splice(indicesToDelete[i], 1);
  66121. }
  66122. for (var renderEffectName in this._renderEffects) {
  66123. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66124. this._renderEffects[renderEffectName]._attachCameras(cams);
  66125. }
  66126. }
  66127. };
  66128. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66129. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66130. if (!cams) {
  66131. return;
  66132. }
  66133. for (var renderEffectName in this._renderEffects) {
  66134. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66135. this._renderEffects[renderEffectName]._detachCameras(cams);
  66136. }
  66137. }
  66138. for (var i = 0; i < cams.length; i++) {
  66139. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66140. }
  66141. };
  66142. PostProcessRenderPipeline.prototype._update = function () {
  66143. for (var renderEffectName in this._renderEffects) {
  66144. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66145. this._renderEffects[renderEffectName]._update();
  66146. }
  66147. }
  66148. for (var i = 0; i < this._cameras.length; i++) {
  66149. var cameraName = this._cameras[i].name;
  66150. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66151. this._renderEffectsForIsolatedPass[cameraName]._update();
  66152. }
  66153. }
  66154. };
  66155. PostProcessRenderPipeline.prototype._reset = function () {
  66156. this._renderEffects = {};
  66157. this._renderEffectsForIsolatedPass = new Array();
  66158. };
  66159. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66160. // 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)
  66161. var effectKeys = Object.keys(this._renderEffects);
  66162. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66163. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66164. if (postProcesses) {
  66165. postProcesses[0].samples = 4;
  66166. return true;
  66167. }
  66168. }
  66169. return false;
  66170. };
  66171. PostProcessRenderPipeline.prototype.dispose = function () {
  66172. // Must be implemented by children
  66173. };
  66174. __decorate([
  66175. BABYLON.serialize()
  66176. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66177. return PostProcessRenderPipeline;
  66178. }());
  66179. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66180. })(BABYLON || (BABYLON = {}));
  66181. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66182. var BABYLON;
  66183. (function (BABYLON) {
  66184. /**
  66185. * This represents a depth renderer in Babylon.
  66186. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66187. */
  66188. var DepthRenderer = /** @class */ (function () {
  66189. /**
  66190. * Instantiates a depth renderer
  66191. * @param scene The scene the renderer belongs to
  66192. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66193. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66194. */
  66195. function DepthRenderer(scene, type, camera) {
  66196. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66197. if (camera === void 0) { camera = null; }
  66198. var _this = this;
  66199. this._scene = scene;
  66200. this._camera = camera;
  66201. var engine = scene.getEngine();
  66202. // Render target
  66203. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66204. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66205. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66206. this._depthMap.refreshRate = 1;
  66207. this._depthMap.renderParticles = false;
  66208. this._depthMap.renderList = null;
  66209. // Camera to get depth map from to support multiple concurrent cameras
  66210. this._depthMap.activeCamera = this._camera;
  66211. this._depthMap.ignoreCameraViewport = true;
  66212. this._depthMap.useCameraPostProcesses = false;
  66213. // set default depth value to 1.0 (far away)
  66214. this._depthMap.onClearObservable.add(function (engine) {
  66215. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66216. });
  66217. // Custom render function
  66218. var renderSubMesh = function (subMesh) {
  66219. var mesh = subMesh.getRenderingMesh();
  66220. var scene = _this._scene;
  66221. var engine = scene.getEngine();
  66222. var material = subMesh.getMaterial();
  66223. if (!material) {
  66224. return;
  66225. }
  66226. // Culling and reverse (right handed system)
  66227. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66228. // Managing instances
  66229. var batch = mesh._getInstancesRenderList(subMesh._id);
  66230. if (batch.mustReturn) {
  66231. return;
  66232. }
  66233. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66234. var camera = _this._camera || scene.activeCamera;
  66235. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66236. engine.enableEffect(_this._effect);
  66237. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66238. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66239. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66240. // Alpha test
  66241. if (material && material.needAlphaTesting()) {
  66242. var alphaTexture = material.getAlphaTestTexture();
  66243. if (alphaTexture) {
  66244. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66245. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66246. }
  66247. }
  66248. // Bones
  66249. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66250. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66251. }
  66252. // Draw
  66253. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66254. }
  66255. };
  66256. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66257. var index;
  66258. if (depthOnlySubMeshes.length) {
  66259. engine.setColorWrite(false);
  66260. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66261. renderSubMesh(depthOnlySubMeshes.data[index]);
  66262. }
  66263. engine.setColorWrite(true);
  66264. }
  66265. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66266. renderSubMesh(opaqueSubMeshes.data[index]);
  66267. }
  66268. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66269. renderSubMesh(alphaTestSubMeshes.data[index]);
  66270. }
  66271. };
  66272. }
  66273. /**
  66274. * Creates the depth rendering effect and checks if the effect is ready.
  66275. * @param subMesh The submesh to be used to render the depth map of
  66276. * @param useInstances If multiple world instances should be used
  66277. * @returns if the depth renderer is ready to render the depth map
  66278. */
  66279. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66280. var material = subMesh.getMaterial();
  66281. if (material.disableDepthWrite) {
  66282. return false;
  66283. }
  66284. var defines = [];
  66285. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66286. var mesh = subMesh.getMesh();
  66287. // Alpha test
  66288. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66289. defines.push("#define ALPHATEST");
  66290. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66291. attribs.push(BABYLON.VertexBuffer.UVKind);
  66292. defines.push("#define UV1");
  66293. }
  66294. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66295. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66296. defines.push("#define UV2");
  66297. }
  66298. }
  66299. // Bones
  66300. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66301. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66302. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66303. if (mesh.numBoneInfluencers > 4) {
  66304. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66305. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66306. }
  66307. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66308. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66309. }
  66310. else {
  66311. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66312. }
  66313. // Instances
  66314. if (useInstances) {
  66315. defines.push("#define INSTANCES");
  66316. attribs.push("world0");
  66317. attribs.push("world1");
  66318. attribs.push("world2");
  66319. attribs.push("world3");
  66320. }
  66321. // Get correct effect
  66322. var join = defines.join("\n");
  66323. if (this._cachedDefines !== join) {
  66324. this._cachedDefines = join;
  66325. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66326. }
  66327. return this._effect.isReady();
  66328. };
  66329. /**
  66330. * Gets the texture which the depth map will be written to.
  66331. * @returns The depth map texture
  66332. */
  66333. DepthRenderer.prototype.getDepthMap = function () {
  66334. return this._depthMap;
  66335. };
  66336. /**
  66337. * Disposes of the depth renderer.
  66338. */
  66339. DepthRenderer.prototype.dispose = function () {
  66340. this._depthMap.dispose();
  66341. };
  66342. return DepthRenderer;
  66343. }());
  66344. BABYLON.DepthRenderer = DepthRenderer;
  66345. })(BABYLON || (BABYLON = {}));
  66346. //# sourceMappingURL=babylon.depthRenderer.js.map
  66347. var BABYLON;
  66348. (function (BABYLON) {
  66349. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66350. __extends(SSAORenderingPipeline, _super);
  66351. /**
  66352. * @constructor
  66353. * @param {string} name - The rendering pipeline name
  66354. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66355. * @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 }
  66356. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66357. */
  66358. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66359. var _this = _super.call(this, scene.getEngine(), name) || this;
  66360. // Members
  66361. /**
  66362. * The PassPostProcess id in the pipeline that contains the original scene color
  66363. * @type {string}
  66364. */
  66365. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66366. /**
  66367. * The SSAO PostProcess id in the pipeline
  66368. * @type {string}
  66369. */
  66370. _this.SSAORenderEffect = "SSAORenderEffect";
  66371. /**
  66372. * The horizontal blur PostProcess id in the pipeline
  66373. * @type {string}
  66374. */
  66375. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66376. /**
  66377. * The vertical blur PostProcess id in the pipeline
  66378. * @type {string}
  66379. */
  66380. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66381. /**
  66382. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66383. * @type {string}
  66384. */
  66385. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66386. /**
  66387. * The output strength of the SSAO post-process. Default value is 1.0.
  66388. * @type {number}
  66389. */
  66390. _this.totalStrength = 1.0;
  66391. /**
  66392. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66393. * @type {number}
  66394. */
  66395. _this.radius = 0.0001;
  66396. /**
  66397. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66398. * Must not be equal to fallOff and superior to fallOff.
  66399. * Default value is 0.975
  66400. * @type {number}
  66401. */
  66402. _this.area = 0.0075;
  66403. /**
  66404. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66405. * Must not be equal to area and inferior to area.
  66406. * Default value is 0.0
  66407. * @type {number}
  66408. */
  66409. _this.fallOff = 0.000001;
  66410. /**
  66411. * The base color of the SSAO post-process
  66412. * The final result is "base + ssao" between [0, 1]
  66413. * @type {number}
  66414. */
  66415. _this.base = 0.5;
  66416. _this._firstUpdate = true;
  66417. _this._scene = scene;
  66418. // Set up assets
  66419. _this._createRandomTexture();
  66420. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66421. var ssaoRatio = ratio.ssaoRatio || ratio;
  66422. var combineRatio = ratio.combineRatio || ratio;
  66423. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66424. _this._createSSAOPostProcess(ssaoRatio);
  66425. _this._createBlurPostProcess(ssaoRatio);
  66426. _this._createSSAOCombinePostProcess(combineRatio);
  66427. // Set up pipeline
  66428. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66429. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66432. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66433. // Finish
  66434. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66435. if (cameras)
  66436. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66437. return _this;
  66438. }
  66439. // Public Methods
  66440. /**
  66441. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66442. */
  66443. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66444. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66445. for (var i = 0; i < this._scene.cameras.length; i++) {
  66446. var camera = this._scene.cameras[i];
  66447. this._originalColorPostProcess.dispose(camera);
  66448. this._ssaoPostProcess.dispose(camera);
  66449. this._blurHPostProcess.dispose(camera);
  66450. this._blurVPostProcess.dispose(camera);
  66451. this._ssaoCombinePostProcess.dispose(camera);
  66452. }
  66453. this._randomTexture.dispose();
  66454. if (disableDepthRender)
  66455. this._scene.disableDepthRenderer();
  66456. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66457. _super.prototype.dispose.call(this);
  66458. };
  66459. // Private Methods
  66460. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66461. var _this = this;
  66462. var size = 16;
  66463. 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);
  66464. 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);
  66465. this._blurHPostProcess.onActivateObservable.add(function () {
  66466. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66467. _this._blurHPostProcess.kernel = size * dw;
  66468. });
  66469. this._blurVPostProcess.onActivateObservable.add(function () {
  66470. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66471. _this._blurVPostProcess.kernel = size * dw;
  66472. });
  66473. };
  66474. SSAORenderingPipeline.prototype._rebuild = function () {
  66475. this._firstUpdate = true;
  66476. _super.prototype._rebuild.call(this);
  66477. };
  66478. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66479. var _this = this;
  66480. var numSamples = 16;
  66481. var sampleSphere = [
  66482. 0.5381, 0.1856, -0.4319,
  66483. 0.1379, 0.2486, 0.4430,
  66484. 0.3371, 0.5679, -0.0057,
  66485. -0.6999, -0.0451, -0.0019,
  66486. 0.0689, -0.1598, -0.8547,
  66487. 0.0560, 0.0069, -0.1843,
  66488. -0.0146, 0.1402, 0.0762,
  66489. 0.0100, -0.1924, -0.0344,
  66490. -0.3577, -0.5301, -0.4358,
  66491. -0.3169, 0.1063, 0.0158,
  66492. 0.0103, -0.5869, 0.0046,
  66493. -0.0897, -0.4940, 0.3287,
  66494. 0.7119, -0.0154, -0.0918,
  66495. -0.0533, 0.0596, -0.5411,
  66496. 0.0352, -0.0631, 0.5460,
  66497. -0.4776, 0.2847, -0.0271
  66498. ];
  66499. var samplesFactor = 1.0 / numSamples;
  66500. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66501. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66502. "area", "fallOff", "base", "range", "viewport"
  66503. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66504. this._ssaoPostProcess.onApply = function (effect) {
  66505. if (_this._firstUpdate) {
  66506. effect.setArray3("sampleSphere", sampleSphere);
  66507. effect.setFloat("samplesFactor", samplesFactor);
  66508. effect.setFloat("randTextureTiles", 4.0);
  66509. }
  66510. effect.setFloat("totalStrength", _this.totalStrength);
  66511. effect.setFloat("radius", _this.radius);
  66512. effect.setFloat("area", _this.area);
  66513. effect.setFloat("fallOff", _this.fallOff);
  66514. effect.setFloat("base", _this.base);
  66515. effect.setTexture("textureSampler", _this._depthTexture);
  66516. effect.setTexture("randomSampler", _this._randomTexture);
  66517. };
  66518. };
  66519. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66520. var _this = this;
  66521. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66522. this._ssaoCombinePostProcess.onApply = function (effect) {
  66523. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66524. };
  66525. };
  66526. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66527. var size = 512;
  66528. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66529. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66530. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66531. var context = this._randomTexture.getContext();
  66532. var rand = function (min, max) {
  66533. return Math.random() * (max - min) + min;
  66534. };
  66535. var randVector = BABYLON.Vector3.Zero();
  66536. for (var x = 0; x < size; x++) {
  66537. for (var y = 0; y < size; y++) {
  66538. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66539. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66540. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66541. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66542. context.fillRect(x, y, 1, 1);
  66543. }
  66544. }
  66545. this._randomTexture.update(false);
  66546. };
  66547. __decorate([
  66548. BABYLON.serialize()
  66549. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66550. __decorate([
  66551. BABYLON.serialize()
  66552. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66553. __decorate([
  66554. BABYLON.serialize()
  66555. ], SSAORenderingPipeline.prototype, "area", void 0);
  66556. __decorate([
  66557. BABYLON.serialize()
  66558. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66559. __decorate([
  66560. BABYLON.serialize()
  66561. ], SSAORenderingPipeline.prototype, "base", void 0);
  66562. return SSAORenderingPipeline;
  66563. }(BABYLON.PostProcessRenderPipeline));
  66564. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66565. })(BABYLON || (BABYLON = {}));
  66566. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66567. var BABYLON;
  66568. (function (BABYLON) {
  66569. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66570. __extends(SSAO2RenderingPipeline, _super);
  66571. /**
  66572. * @constructor
  66573. * @param {string} name - The rendering pipeline name
  66574. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66575. * @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 }
  66576. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66577. */
  66578. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66579. var _this = _super.call(this, scene.getEngine(), name) || this;
  66580. // Members
  66581. /**
  66582. * The PassPostProcess id in the pipeline that contains the original scene color
  66583. * @type {string}
  66584. */
  66585. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66586. /**
  66587. * The SSAO PostProcess id in the pipeline
  66588. * @type {string}
  66589. */
  66590. _this.SSAORenderEffect = "SSAORenderEffect";
  66591. /**
  66592. * The horizontal blur PostProcess id in the pipeline
  66593. * @type {string}
  66594. */
  66595. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66596. /**
  66597. * The vertical blur PostProcess id in the pipeline
  66598. * @type {string}
  66599. */
  66600. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66601. /**
  66602. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66603. * @type {string}
  66604. */
  66605. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66606. /**
  66607. * The output strength of the SSAO post-process. Default value is 1.0.
  66608. * @type {number}
  66609. */
  66610. _this.totalStrength = 1.0;
  66611. /**
  66612. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66613. * @type {number}
  66614. */
  66615. _this.maxZ = 100.0;
  66616. /**
  66617. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66618. * @type {number}
  66619. */
  66620. _this.minZAspect = 0.2;
  66621. /**
  66622. * Number of samples used for the SSAO calculations. Default value is 8
  66623. * @type {number}
  66624. */
  66625. _this._samples = 8;
  66626. /**
  66627. * Are we using bilateral blur ?
  66628. * @type {boolean}
  66629. */
  66630. _this._expensiveBlur = true;
  66631. /**
  66632. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66633. * @type {number}
  66634. */
  66635. _this.radius = 2.0;
  66636. /**
  66637. * The base color of the SSAO post-process
  66638. * The final result is "base + ssao" between [0, 1]
  66639. * @type {number}
  66640. */
  66641. _this.base = 0.1;
  66642. _this._firstUpdate = true;
  66643. _this._scene = scene;
  66644. if (!_this.isSupported) {
  66645. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66646. return _this;
  66647. }
  66648. var ssaoRatio = ratio.ssaoRatio || ratio;
  66649. var blurRatio = ratio.blurRatio || ratio;
  66650. // Set up assets
  66651. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66652. _this._createRandomTexture();
  66653. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66654. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66655. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66656. _this._createSSAOPostProcess(1.0);
  66657. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66658. _this._createSSAOCombinePostProcess(blurRatio);
  66659. // Set up pipeline
  66660. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66661. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66662. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66663. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66664. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66665. // Finish
  66666. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66667. if (cameras)
  66668. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66669. return _this;
  66670. }
  66671. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66672. get: function () {
  66673. return this._samples;
  66674. },
  66675. set: function (n) {
  66676. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66677. this._samples = n;
  66678. this._sampleSphere = this._generateHemisphere();
  66679. this._firstUpdate = true;
  66680. },
  66681. enumerable: true,
  66682. configurable: true
  66683. });
  66684. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66685. get: function () {
  66686. return this._expensiveBlur;
  66687. },
  66688. set: function (b) {
  66689. 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"]);
  66690. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66691. this._expensiveBlur = b;
  66692. this._firstUpdate = true;
  66693. },
  66694. enumerable: true,
  66695. configurable: true
  66696. });
  66697. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66698. /**
  66699. * Support test.
  66700. * @type {boolean}
  66701. */
  66702. get: function () {
  66703. var engine = BABYLON.Engine.LastCreatedEngine;
  66704. if (!engine) {
  66705. return false;
  66706. }
  66707. return engine.getCaps().drawBuffersExtension;
  66708. },
  66709. enumerable: true,
  66710. configurable: true
  66711. });
  66712. // Public Methods
  66713. /**
  66714. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66715. */
  66716. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66717. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66718. for (var i = 0; i < this._scene.cameras.length; i++) {
  66719. var camera = this._scene.cameras[i];
  66720. this._originalColorPostProcess.dispose(camera);
  66721. this._ssaoPostProcess.dispose(camera);
  66722. this._blurHPostProcess.dispose(camera);
  66723. this._blurVPostProcess.dispose(camera);
  66724. this._ssaoCombinePostProcess.dispose(camera);
  66725. }
  66726. this._randomTexture.dispose();
  66727. if (disableGeometryBufferRenderer)
  66728. this._scene.disableGeometryBufferRenderer();
  66729. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66730. _super.prototype.dispose.call(this);
  66731. };
  66732. // Private Methods
  66733. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66734. var _this = this;
  66735. this._samplerOffsets = [];
  66736. var expensive = this.expensiveBlur;
  66737. for (var i = -8; i < 8; i++) {
  66738. this._samplerOffsets.push(i * 2 + 0.5);
  66739. }
  66740. 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");
  66741. this._blurHPostProcess.onApply = function (effect) {
  66742. if (!_this._scene.activeCamera) {
  66743. return;
  66744. }
  66745. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66746. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66747. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66748. effect.setFloat("radius", _this.radius);
  66749. effect.setTexture("depthSampler", _this._depthTexture);
  66750. if (_this._firstUpdate) {
  66751. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66752. }
  66753. };
  66754. 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");
  66755. this._blurVPostProcess.onApply = function (effect) {
  66756. if (!_this._scene.activeCamera) {
  66757. return;
  66758. }
  66759. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66760. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66761. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66762. effect.setFloat("radius", _this.radius);
  66763. effect.setTexture("depthSampler", _this._depthTexture);
  66764. if (_this._firstUpdate) {
  66765. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66766. _this._firstUpdate = false;
  66767. }
  66768. };
  66769. };
  66770. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66771. this._firstUpdate = true;
  66772. _super.prototype._rebuild.call(this);
  66773. };
  66774. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66775. var numSamples = this.samples;
  66776. var result = [];
  66777. var vector, scale;
  66778. var rand = function (min, max) {
  66779. return Math.random() * (max - min) + min;
  66780. };
  66781. var i = 0;
  66782. while (i < numSamples) {
  66783. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66784. vector.normalize();
  66785. scale = i / numSamples;
  66786. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66787. vector.scaleInPlace(scale);
  66788. result.push(vector.x, vector.y, vector.z);
  66789. i++;
  66790. }
  66791. return result;
  66792. };
  66793. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66794. var _this = this;
  66795. var numSamples = this.samples;
  66796. this._sampleSphere = this._generateHemisphere();
  66797. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66798. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66799. "base", "range", "projection", "near", "far", "texelSize",
  66800. "xViewport", "yViewport", "maxZ", "minZAspect"
  66801. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66802. this._ssaoPostProcess.onApply = function (effect) {
  66803. if (_this._firstUpdate) {
  66804. effect.setArray3("sampleSphere", _this._sampleSphere);
  66805. effect.setFloat("randTextureTiles", 4.0);
  66806. }
  66807. if (!_this._scene.activeCamera) {
  66808. return;
  66809. }
  66810. effect.setFloat("samplesFactor", 1 / _this.samples);
  66811. effect.setFloat("totalStrength", _this.totalStrength);
  66812. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66813. effect.setFloat("radius", _this.radius);
  66814. effect.setFloat("maxZ", _this.maxZ);
  66815. effect.setFloat("minZAspect", _this.minZAspect);
  66816. effect.setFloat("base", _this.base);
  66817. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66818. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66819. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66820. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66821. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66822. effect.setTexture("textureSampler", _this._depthTexture);
  66823. effect.setTexture("normalSampler", _this._normalTexture);
  66824. effect.setTexture("randomSampler", _this._randomTexture);
  66825. };
  66826. };
  66827. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66828. var _this = this;
  66829. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66830. this._ssaoCombinePostProcess.onApply = function (effect) {
  66831. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66832. };
  66833. };
  66834. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66835. var size = 512;
  66836. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66837. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66838. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66839. var context = this._randomTexture.getContext();
  66840. var rand = function (min, max) {
  66841. return Math.random() * (max - min) + min;
  66842. };
  66843. var randVector = BABYLON.Vector3.Zero();
  66844. for (var x = 0; x < size; x++) {
  66845. for (var y = 0; y < size; y++) {
  66846. randVector.x = rand(0.0, 1.0);
  66847. randVector.y = rand(0.0, 1.0);
  66848. randVector.z = 0.0;
  66849. randVector.normalize();
  66850. randVector.scaleInPlace(255);
  66851. randVector.x = Math.floor(randVector.x);
  66852. randVector.y = Math.floor(randVector.y);
  66853. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66854. context.fillRect(x, y, 1, 1);
  66855. }
  66856. }
  66857. this._randomTexture.update(false);
  66858. };
  66859. __decorate([
  66860. BABYLON.serialize()
  66861. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66862. __decorate([
  66863. BABYLON.serialize()
  66864. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66865. __decorate([
  66866. BABYLON.serialize()
  66867. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66868. __decorate([
  66869. BABYLON.serialize("samples")
  66870. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66871. __decorate([
  66872. BABYLON.serialize("expensiveBlur")
  66873. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66874. __decorate([
  66875. BABYLON.serialize()
  66876. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66877. __decorate([
  66878. BABYLON.serialize()
  66879. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66880. return SSAO2RenderingPipeline;
  66881. }(BABYLON.PostProcessRenderPipeline));
  66882. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66883. })(BABYLON || (BABYLON = {}));
  66884. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66885. // BABYLON.JS Chromatic Aberration GLSL Shader
  66886. // Author: Olivier Guyot
  66887. // Separates very slightly R, G and B colors on the edges of the screen
  66888. // Inspired by Francois Tarlier & Martins Upitis
  66889. var BABYLON;
  66890. (function (BABYLON) {
  66891. var LensRenderingPipeline = /** @class */ (function (_super) {
  66892. __extends(LensRenderingPipeline, _super);
  66893. /**
  66894. * @constructor
  66895. *
  66896. * Effect parameters are as follow:
  66897. * {
  66898. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66899. * edge_blur: number; // from 0 to x (1 for realism)
  66900. * distortion: number; // from 0 to x (1 for realism)
  66901. * grain_amount: number; // from 0 to 1
  66902. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66903. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66904. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66905. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66906. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66907. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66908. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66909. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66910. * }
  66911. * Note: if an effect parameter is unset, effect is disabled
  66912. *
  66913. * @param {string} name - The rendering pipeline name
  66914. * @param {object} parameters - An object containing all parameters (see above)
  66915. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66916. * @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)
  66917. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66918. */
  66919. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66920. if (ratio === void 0) { ratio = 1.0; }
  66921. var _this = _super.call(this, scene.getEngine(), name) || this;
  66922. // Lens effects can be of the following:
  66923. // - chromatic aberration (slight shift of RGB colors)
  66924. // - blur on the edge of the lens
  66925. // - lens distortion
  66926. // - depth-of-field blur & highlights enhancing
  66927. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66928. // - grain effect (noise or custom texture)
  66929. // Two additional texture samplers are needed:
  66930. // - depth map (for depth-of-field)
  66931. // - grain texture
  66932. /**
  66933. * The chromatic aberration PostProcess id in the pipeline
  66934. * @type {string}
  66935. */
  66936. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66937. /**
  66938. * The highlights enhancing PostProcess id in the pipeline
  66939. * @type {string}
  66940. */
  66941. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66942. /**
  66943. * The depth-of-field PostProcess id in the pipeline
  66944. * @type {string}
  66945. */
  66946. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66947. _this._scene = scene;
  66948. // Fetch texture samplers
  66949. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66950. if (parameters.grain_texture) {
  66951. _this._grainTexture = parameters.grain_texture;
  66952. }
  66953. else {
  66954. _this._createGrainTexture();
  66955. }
  66956. // save parameters
  66957. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66958. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66959. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66960. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66961. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66962. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66963. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66964. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66965. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66966. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66967. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66968. // Create effects
  66969. _this._createChromaticAberrationPostProcess(ratio);
  66970. _this._createHighlightsPostProcess(ratio);
  66971. _this._createDepthOfFieldPostProcess(ratio / 4);
  66972. // Set up pipeline
  66973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66976. if (_this._highlightsGain === -1) {
  66977. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66978. }
  66979. // Finish
  66980. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66981. if (cameras) {
  66982. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66983. }
  66984. return _this;
  66985. }
  66986. // public methods (self explanatory)
  66987. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66988. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66989. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66990. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66991. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66992. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66993. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66994. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66995. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66996. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66997. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66998. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66999. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67000. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67001. };
  67002. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67003. this._highlightsPostProcess.updateEffect();
  67004. };
  67005. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67006. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67007. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67008. this._highlightsGain = amount;
  67009. };
  67010. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67011. if (this._highlightsGain === -1) {
  67012. this._highlightsGain = 1.0;
  67013. }
  67014. this._highlightsThreshold = amount;
  67015. };
  67016. LensRenderingPipeline.prototype.disableHighlights = function () {
  67017. this._highlightsGain = -1;
  67018. };
  67019. /**
  67020. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67021. */
  67022. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67023. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67024. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67025. this._chromaticAberrationPostProcess = null;
  67026. this._highlightsPostProcess = null;
  67027. this._depthOfFieldPostProcess = null;
  67028. this._grainTexture.dispose();
  67029. if (disableDepthRender)
  67030. this._scene.disableDepthRenderer();
  67031. };
  67032. // colors shifting and distortion
  67033. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67034. var _this = this;
  67035. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67036. [], // samplers
  67037. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67038. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67039. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67040. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67041. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67042. effect.setFloat('radialIntensity', 1);
  67043. effect.setFloat2('direction', 17, 17);
  67044. effect.setFloat2('centerPosition', 0.5, 0.5);
  67045. };
  67046. };
  67047. // highlights enhancing
  67048. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67049. var _this = this;
  67050. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67051. [], // samplers
  67052. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67053. this._highlightsPostProcess.onApply = function (effect) {
  67054. effect.setFloat('gain', _this._highlightsGain);
  67055. effect.setFloat('threshold', _this._highlightsThreshold);
  67056. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67057. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67058. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67059. };
  67060. };
  67061. // colors shifting and distortion
  67062. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67063. var _this = this;
  67064. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67065. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67066. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67067. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67068. this._depthOfFieldPostProcess.onApply = function (effect) {
  67069. effect.setTexture("depthSampler", _this._depthTexture);
  67070. effect.setTexture("grainSampler", _this._grainTexture);
  67071. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67072. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67073. effect.setFloat('grain_amount', _this._grainAmount);
  67074. effect.setBool('blur_noise', _this._blurNoise);
  67075. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67076. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67077. effect.setFloat('distortion', _this._distortion);
  67078. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67079. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67080. effect.setFloat('aperture', _this._dofAperture);
  67081. effect.setFloat('darken', _this._dofDarken);
  67082. effect.setFloat('edge_blur', _this._edgeBlur);
  67083. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67084. if (_this._scene.activeCamera) {
  67085. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67086. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67087. }
  67088. };
  67089. };
  67090. // creates a black and white random noise texture, 512x512
  67091. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67092. var size = 512;
  67093. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67094. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67095. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67096. var context = this._grainTexture.getContext();
  67097. var rand = function (min, max) {
  67098. return Math.random() * (max - min) + min;
  67099. };
  67100. var value;
  67101. for (var x = 0; x < size; x++) {
  67102. for (var y = 0; y < size; y++) {
  67103. value = Math.floor(rand(0.42, 0.58) * 255);
  67104. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67105. context.fillRect(x, y, 1, 1);
  67106. }
  67107. }
  67108. this._grainTexture.update(false);
  67109. };
  67110. return LensRenderingPipeline;
  67111. }(BABYLON.PostProcessRenderPipeline));
  67112. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67113. })(BABYLON || (BABYLON = {}));
  67114. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67115. var BABYLON;
  67116. (function (BABYLON) {
  67117. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67118. __extends(StandardRenderingPipeline, _super);
  67119. /**
  67120. * @constructor
  67121. * @param {string} name - The rendering pipeline name
  67122. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67123. * @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)
  67124. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67125. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67126. */
  67127. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67128. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67129. var _this = _super.call(this, scene.getEngine(), name) || this;
  67130. _this.downSampleX4PostProcess = null;
  67131. _this.brightPassPostProcess = null;
  67132. _this.blurHPostProcesses = [];
  67133. _this.blurVPostProcesses = [];
  67134. _this.textureAdderPostProcess = null;
  67135. _this.volumetricLightPostProcess = null;
  67136. _this.volumetricLightSmoothXPostProcess = null;
  67137. _this.volumetricLightSmoothYPostProcess = null;
  67138. _this.volumetricLightMergePostProces = null;
  67139. _this.volumetricLightFinalPostProcess = null;
  67140. _this.luminancePostProcess = null;
  67141. _this.luminanceDownSamplePostProcesses = [];
  67142. _this.hdrPostProcess = null;
  67143. _this.textureAdderFinalPostProcess = null;
  67144. _this.lensFlareFinalPostProcess = null;
  67145. _this.hdrFinalPostProcess = null;
  67146. _this.lensFlarePostProcess = null;
  67147. _this.lensFlareComposePostProcess = null;
  67148. _this.motionBlurPostProcess = null;
  67149. _this.depthOfFieldPostProcess = null;
  67150. // Values
  67151. _this.brightThreshold = 1.0;
  67152. _this.blurWidth = 512.0;
  67153. _this.horizontalBlur = false;
  67154. _this.exposure = 1.0;
  67155. _this.lensTexture = null;
  67156. _this.volumetricLightCoefficient = 0.2;
  67157. _this.volumetricLightPower = 4.0;
  67158. _this.volumetricLightBlurScale = 64.0;
  67159. _this.sourceLight = null;
  67160. _this.hdrMinimumLuminance = 1.0;
  67161. _this.hdrDecreaseRate = 0.5;
  67162. _this.hdrIncreaseRate = 0.5;
  67163. _this.lensColorTexture = null;
  67164. _this.lensFlareStrength = 20.0;
  67165. _this.lensFlareGhostDispersal = 1.4;
  67166. _this.lensFlareHaloWidth = 0.7;
  67167. _this.lensFlareDistortionStrength = 16.0;
  67168. _this.lensStarTexture = null;
  67169. _this.lensFlareDirtTexture = null;
  67170. _this.depthOfFieldDistance = 10.0;
  67171. _this.depthOfFieldBlurWidth = 64.0;
  67172. _this.motionStrength = 1.0;
  67173. // IAnimatable
  67174. _this.animations = [];
  67175. _this._currentDepthOfFieldSource = null;
  67176. _this._hdrCurrentLuminance = 1.0;
  67177. // Getters and setters
  67178. _this._bloomEnabled = true;
  67179. _this._depthOfFieldEnabled = false;
  67180. _this._vlsEnabled = false;
  67181. _this._lensFlareEnabled = false;
  67182. _this._hdrEnabled = false;
  67183. _this._motionBlurEnabled = false;
  67184. _this._motionBlurSamples = 64.0;
  67185. _this._volumetricLightStepsCount = 50.0;
  67186. _this._cameras = cameras || [];
  67187. // Initialize
  67188. _this._scene = scene;
  67189. _this._basePostProcess = originalPostProcess;
  67190. _this._ratio = ratio;
  67191. // Misc
  67192. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67193. // Finish
  67194. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67195. _this._buildPipeline();
  67196. return _this;
  67197. }
  67198. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67199. get: function () {
  67200. return this._bloomEnabled;
  67201. },
  67202. set: function (enabled) {
  67203. if (this._bloomEnabled === enabled) {
  67204. return;
  67205. }
  67206. this._bloomEnabled = enabled;
  67207. this._buildPipeline();
  67208. },
  67209. enumerable: true,
  67210. configurable: true
  67211. });
  67212. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67213. get: function () {
  67214. return this._depthOfFieldEnabled;
  67215. },
  67216. set: function (enabled) {
  67217. if (this._depthOfFieldEnabled === enabled) {
  67218. return;
  67219. }
  67220. this._depthOfFieldEnabled = enabled;
  67221. this._buildPipeline();
  67222. },
  67223. enumerable: true,
  67224. configurable: true
  67225. });
  67226. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67227. get: function () {
  67228. return this._lensFlareEnabled;
  67229. },
  67230. set: function (enabled) {
  67231. if (this._lensFlareEnabled === enabled) {
  67232. return;
  67233. }
  67234. this._lensFlareEnabled = enabled;
  67235. this._buildPipeline();
  67236. },
  67237. enumerable: true,
  67238. configurable: true
  67239. });
  67240. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67241. get: function () {
  67242. return this._hdrEnabled;
  67243. },
  67244. set: function (enabled) {
  67245. if (this._hdrEnabled === enabled) {
  67246. return;
  67247. }
  67248. this._hdrEnabled = enabled;
  67249. this._buildPipeline();
  67250. },
  67251. enumerable: true,
  67252. configurable: true
  67253. });
  67254. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67255. get: function () {
  67256. return this._vlsEnabled;
  67257. },
  67258. set: function (enabled) {
  67259. if (this._vlsEnabled === enabled) {
  67260. return;
  67261. }
  67262. if (enabled) {
  67263. var geometry = this._scene.enableGeometryBufferRenderer();
  67264. if (!geometry) {
  67265. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67266. return;
  67267. }
  67268. }
  67269. this._vlsEnabled = enabled;
  67270. this._buildPipeline();
  67271. },
  67272. enumerable: true,
  67273. configurable: true
  67274. });
  67275. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67276. get: function () {
  67277. return this._motionBlurEnabled;
  67278. },
  67279. set: function (enabled) {
  67280. if (this._motionBlurEnabled === enabled) {
  67281. return;
  67282. }
  67283. this._motionBlurEnabled = enabled;
  67284. this._buildPipeline();
  67285. },
  67286. enumerable: true,
  67287. configurable: true
  67288. });
  67289. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67290. get: function () {
  67291. return this._volumetricLightStepsCount;
  67292. },
  67293. set: function (count) {
  67294. if (this.volumetricLightPostProcess) {
  67295. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67296. }
  67297. this._volumetricLightStepsCount = count;
  67298. },
  67299. enumerable: true,
  67300. configurable: true
  67301. });
  67302. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67303. get: function () {
  67304. return this._motionBlurSamples;
  67305. },
  67306. set: function (samples) {
  67307. if (this.motionBlurPostProcess) {
  67308. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67309. }
  67310. this._motionBlurSamples = samples;
  67311. },
  67312. enumerable: true,
  67313. configurable: true
  67314. });
  67315. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67316. var _this = this;
  67317. var ratio = this._ratio;
  67318. var scene = this._scene;
  67319. this._disposePostProcesses();
  67320. this._reset();
  67321. // Create pass post-process
  67322. if (!this._basePostProcess) {
  67323. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67324. this.originalPostProcess.onApply = function (effect) {
  67325. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67326. };
  67327. }
  67328. else {
  67329. this.originalPostProcess = this._basePostProcess;
  67330. }
  67331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67332. this._currentDepthOfFieldSource = this.originalPostProcess;
  67333. if (this._vlsEnabled) {
  67334. // Create volumetric light
  67335. this._createVolumetricLightPostProcess(scene, ratio);
  67336. // Create volumetric light final post-process
  67337. 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);
  67338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67339. }
  67340. if (this._bloomEnabled) {
  67341. // Create down sample X4 post-process
  67342. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67343. // Create bright pass post-process
  67344. this._createBrightPassPostProcess(scene, ratio / 2);
  67345. // Create gaussian blur post-processes (down sampling blurs)
  67346. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67347. // Create texture adder post-process
  67348. this._createTextureAdderPostProcess(scene, ratio);
  67349. // Create depth-of-field source post-process
  67350. 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);
  67351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67352. }
  67353. if (this._lensFlareEnabled) {
  67354. // Create lens flare post-process
  67355. this._createLensFlarePostProcess(scene, ratio);
  67356. // Create depth-of-field source post-process post lens-flare and disable it now
  67357. 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);
  67358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67359. }
  67360. if (this._hdrEnabled) {
  67361. // Create luminance
  67362. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67363. // Create HDR
  67364. this._createHdrPostProcess(scene, ratio);
  67365. // Create depth-of-field source post-process post hdr and disable it now
  67366. 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);
  67367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67368. }
  67369. if (this._depthOfFieldEnabled) {
  67370. // Create gaussian blur used by depth-of-field
  67371. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67372. // Create depth-of-field post-process
  67373. this._createDepthOfFieldPostProcess(scene, ratio);
  67374. }
  67375. if (this._motionBlurEnabled) {
  67376. // Create motion blur post-process
  67377. this._createMotionBlurPostProcess(scene, ratio);
  67378. }
  67379. if (this._cameras !== null) {
  67380. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67381. }
  67382. };
  67383. // Down Sample X4 Post-Processs
  67384. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67385. var _this = this;
  67386. var downSampleX4Offsets = new Array(32);
  67387. 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);
  67388. this.downSampleX4PostProcess.onApply = function (effect) {
  67389. var id = 0;
  67390. var width = _this.downSampleX4PostProcess.width;
  67391. var height = _this.downSampleX4PostProcess.height;
  67392. for (var i = -2; i < 2; i++) {
  67393. for (var j = -2; j < 2; j++) {
  67394. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67395. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67396. id += 2;
  67397. }
  67398. }
  67399. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67400. };
  67401. // Add to pipeline
  67402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67403. };
  67404. // Brightpass Post-Process
  67405. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67406. var _this = this;
  67407. var brightOffsets = new Array(8);
  67408. 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);
  67409. this.brightPassPostProcess.onApply = function (effect) {
  67410. var sU = (1.0 / _this.brightPassPostProcess.width);
  67411. var sV = (1.0 / _this.brightPassPostProcess.height);
  67412. brightOffsets[0] = -0.5 * sU;
  67413. brightOffsets[1] = 0.5 * sV;
  67414. brightOffsets[2] = 0.5 * sU;
  67415. brightOffsets[3] = 0.5 * sV;
  67416. brightOffsets[4] = -0.5 * sU;
  67417. brightOffsets[5] = -0.5 * sV;
  67418. brightOffsets[6] = 0.5 * sU;
  67419. brightOffsets[7] = -0.5 * sV;
  67420. effect.setArray2("dsOffsets", brightOffsets);
  67421. effect.setFloat("brightThreshold", _this.brightThreshold);
  67422. };
  67423. // Add to pipeline
  67424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67425. };
  67426. // Create blur H&V post-processes
  67427. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67428. var _this = this;
  67429. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67430. var engine = scene.getEngine();
  67431. 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);
  67432. 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);
  67433. blurX.onActivateObservable.add(function () {
  67434. var dw = blurX.width / engine.getRenderWidth();
  67435. blurX.kernel = _this[blurWidthKey] * dw;
  67436. });
  67437. blurY.onActivateObservable.add(function () {
  67438. var dw = blurY.height / engine.getRenderHeight();
  67439. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67440. });
  67441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67442. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67443. this.blurHPostProcesses.push(blurX);
  67444. this.blurVPostProcesses.push(blurY);
  67445. };
  67446. // Create texture adder post-process
  67447. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67448. var _this = this;
  67449. 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);
  67450. this.textureAdderPostProcess.onApply = function (effect) {
  67451. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67452. effect.setTexture("lensSampler", _this.lensTexture);
  67453. effect.setFloat("exposure", _this.exposure);
  67454. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67455. };
  67456. // Add to pipeline
  67457. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67458. };
  67459. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67460. var _this = this;
  67461. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67462. geometryRenderer.enablePosition = true;
  67463. var geometry = geometryRenderer.getGBuffer();
  67464. // Base post-process
  67465. 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));
  67466. var depthValues = BABYLON.Vector2.Zero();
  67467. this.volumetricLightPostProcess.onApply = function (effect) {
  67468. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67469. var generator = _this.sourceLight.getShadowGenerator();
  67470. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67471. effect.setTexture("positionSampler", geometry.textures[2]);
  67472. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67473. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67474. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67475. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67476. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67477. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67478. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67479. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67480. effect.setVector2("depthValues", depthValues);
  67481. }
  67482. };
  67483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67484. // Smooth
  67485. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67486. // Merge
  67487. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67488. this.volumetricLightMergePostProces.onApply = function (effect) {
  67489. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67490. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67491. };
  67492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67493. };
  67494. // Create luminance
  67495. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67496. var _this = this;
  67497. // Create luminance
  67498. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67499. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67500. var offsets = [];
  67501. this.luminancePostProcess.onApply = function (effect) {
  67502. var sU = (1.0 / _this.luminancePostProcess.width);
  67503. var sV = (1.0 / _this.luminancePostProcess.height);
  67504. offsets[0] = -0.5 * sU;
  67505. offsets[1] = 0.5 * sV;
  67506. offsets[2] = 0.5 * sU;
  67507. offsets[3] = 0.5 * sV;
  67508. offsets[4] = -0.5 * sU;
  67509. offsets[5] = -0.5 * sV;
  67510. offsets[6] = 0.5 * sU;
  67511. offsets[7] = -0.5 * sV;
  67512. effect.setArray2("lumOffsets", offsets);
  67513. };
  67514. // Add to pipeline
  67515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67516. // Create down sample luminance
  67517. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67518. var size = Math.pow(3, i);
  67519. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67520. if (i === 0) {
  67521. defines += "#define FINAL_DOWN_SAMPLER";
  67522. }
  67523. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67524. this.luminanceDownSamplePostProcesses.push(postProcess);
  67525. }
  67526. // Create callbacks and add effects
  67527. var lastLuminance = this.luminancePostProcess;
  67528. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67529. var downSampleOffsets = new Array(18);
  67530. pp.onApply = function (effect) {
  67531. if (!lastLuminance) {
  67532. return;
  67533. }
  67534. var id = 0;
  67535. for (var x = -1; x < 2; x++) {
  67536. for (var y = -1; y < 2; y++) {
  67537. downSampleOffsets[id] = x / lastLuminance.width;
  67538. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67539. id += 2;
  67540. }
  67541. }
  67542. effect.setArray2("dsOffsets", downSampleOffsets);
  67543. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67544. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67545. lastLuminance = _this.luminancePostProcess;
  67546. }
  67547. else {
  67548. lastLuminance = pp;
  67549. }
  67550. };
  67551. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67552. pp.onAfterRender = function (effect) {
  67553. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67554. 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);
  67555. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67556. };
  67557. }
  67558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67559. });
  67560. };
  67561. // Create HDR post-process
  67562. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67563. var _this = this;
  67564. 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);
  67565. var outputLiminance = 1;
  67566. var time = 0;
  67567. var lastTime = 0;
  67568. this.hdrPostProcess.onApply = function (effect) {
  67569. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67570. time += scene.getEngine().getDeltaTime();
  67571. if (outputLiminance < 0) {
  67572. outputLiminance = _this._hdrCurrentLuminance;
  67573. }
  67574. else {
  67575. var dt = (lastTime - time) / 1000.0;
  67576. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67577. outputLiminance += _this.hdrDecreaseRate * dt;
  67578. }
  67579. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67580. outputLiminance -= _this.hdrIncreaseRate * dt;
  67581. }
  67582. else {
  67583. outputLiminance = _this._hdrCurrentLuminance;
  67584. }
  67585. }
  67586. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67587. effect.setFloat("averageLuminance", outputLiminance);
  67588. lastTime = time;
  67589. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67590. };
  67591. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67592. };
  67593. // Create lens flare post-process
  67594. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67595. var _this = this;
  67596. 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);
  67597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67598. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67599. 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);
  67600. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67601. var resolution = new BABYLON.Vector2(0, 0);
  67602. // Lens flare
  67603. this.lensFlarePostProcess.onApply = function (effect) {
  67604. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67605. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67606. effect.setFloat("strength", _this.lensFlareStrength);
  67607. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67608. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67609. // Shift
  67610. resolution.x = _this.lensFlarePostProcess.width;
  67611. resolution.y = _this.lensFlarePostProcess.height;
  67612. effect.setVector2("resolution", resolution);
  67613. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67614. };
  67615. // Compose
  67616. 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);
  67617. 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);
  67618. this.lensFlareComposePostProcess.onApply = function (effect) {
  67619. if (!_this._scene.activeCamera) {
  67620. return;
  67621. }
  67622. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67623. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67624. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67625. // Lens start rotation matrix
  67626. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67627. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67628. 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));
  67629. camRot *= 4.0;
  67630. 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);
  67631. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67632. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67633. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67634. };
  67635. };
  67636. // Create depth-of-field post-process
  67637. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67638. var _this = this;
  67639. 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);
  67640. this.depthOfFieldPostProcess.onApply = function (effect) {
  67641. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67642. effect.setTexture("depthSampler", _this._getDepthTexture());
  67643. effect.setFloat("distance", _this.depthOfFieldDistance);
  67644. };
  67645. // Add to pipeline
  67646. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67647. };
  67648. // Create motion blur post-process
  67649. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67650. var _this = this;
  67651. 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);
  67652. var motionScale = 0;
  67653. var prevViewProjection = BABYLON.Matrix.Identity();
  67654. var invViewProjection = BABYLON.Matrix.Identity();
  67655. var viewProjection = BABYLON.Matrix.Identity();
  67656. var screenSize = BABYLON.Vector2.Zero();
  67657. this.motionBlurPostProcess.onApply = function (effect) {
  67658. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67659. viewProjection.invertToRef(invViewProjection);
  67660. effect.setMatrix("inverseViewProjection", invViewProjection);
  67661. effect.setMatrix("prevViewProjection", prevViewProjection);
  67662. prevViewProjection = viewProjection;
  67663. screenSize.x = _this.motionBlurPostProcess.width;
  67664. screenSize.y = _this.motionBlurPostProcess.height;
  67665. effect.setVector2("screenSize", screenSize);
  67666. motionScale = scene.getEngine().getFps() / 60.0;
  67667. effect.setFloat("motionScale", motionScale);
  67668. effect.setFloat("motionStrength", _this.motionStrength);
  67669. effect.setTexture("depthSampler", _this._getDepthTexture());
  67670. };
  67671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67672. };
  67673. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67674. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67675. var renderer = this._scene.enableGeometryBufferRenderer();
  67676. return renderer.getGBuffer().textures[0];
  67677. }
  67678. return this._scene.enableDepthRenderer().getDepthMap();
  67679. };
  67680. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67681. for (var i = 0; i < this._cameras.length; i++) {
  67682. var camera = this._cameras[i];
  67683. if (this.originalPostProcess) {
  67684. this.originalPostProcess.dispose(camera);
  67685. }
  67686. if (this.downSampleX4PostProcess) {
  67687. this.downSampleX4PostProcess.dispose(camera);
  67688. }
  67689. if (this.brightPassPostProcess) {
  67690. this.brightPassPostProcess.dispose(camera);
  67691. }
  67692. if (this.textureAdderPostProcess) {
  67693. this.textureAdderPostProcess.dispose(camera);
  67694. }
  67695. if (this.textureAdderFinalPostProcess) {
  67696. this.textureAdderFinalPostProcess.dispose(camera);
  67697. }
  67698. if (this.volumetricLightPostProcess) {
  67699. this.volumetricLightPostProcess.dispose(camera);
  67700. }
  67701. if (this.volumetricLightSmoothXPostProcess) {
  67702. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67703. }
  67704. if (this.volumetricLightSmoothYPostProcess) {
  67705. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67706. }
  67707. if (this.volumetricLightMergePostProces) {
  67708. this.volumetricLightMergePostProces.dispose(camera);
  67709. }
  67710. if (this.volumetricLightFinalPostProcess) {
  67711. this.volumetricLightFinalPostProcess.dispose(camera);
  67712. }
  67713. if (this.lensFlarePostProcess) {
  67714. this.lensFlarePostProcess.dispose(camera);
  67715. }
  67716. if (this.lensFlareComposePostProcess) {
  67717. this.lensFlareComposePostProcess.dispose(camera);
  67718. }
  67719. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67720. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67721. }
  67722. if (this.luminancePostProcess) {
  67723. this.luminancePostProcess.dispose(camera);
  67724. }
  67725. if (this.hdrPostProcess) {
  67726. this.hdrPostProcess.dispose(camera);
  67727. }
  67728. if (this.hdrFinalPostProcess) {
  67729. this.hdrFinalPostProcess.dispose(camera);
  67730. }
  67731. if (this.depthOfFieldPostProcess) {
  67732. this.depthOfFieldPostProcess.dispose(camera);
  67733. }
  67734. if (this.motionBlurPostProcess) {
  67735. this.motionBlurPostProcess.dispose(camera);
  67736. }
  67737. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67738. this.blurHPostProcesses[j].dispose(camera);
  67739. }
  67740. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67741. this.blurVPostProcesses[j].dispose(camera);
  67742. }
  67743. }
  67744. this.originalPostProcess = null;
  67745. this.downSampleX4PostProcess = null;
  67746. this.brightPassPostProcess = null;
  67747. this.textureAdderPostProcess = null;
  67748. this.textureAdderFinalPostProcess = null;
  67749. this.volumetricLightPostProcess = null;
  67750. this.volumetricLightSmoothXPostProcess = null;
  67751. this.volumetricLightSmoothYPostProcess = null;
  67752. this.volumetricLightMergePostProces = null;
  67753. this.volumetricLightFinalPostProcess = null;
  67754. this.lensFlarePostProcess = null;
  67755. this.lensFlareComposePostProcess = null;
  67756. this.luminancePostProcess = null;
  67757. this.hdrPostProcess = null;
  67758. this.hdrFinalPostProcess = null;
  67759. this.depthOfFieldPostProcess = null;
  67760. this.motionBlurPostProcess = null;
  67761. this.luminanceDownSamplePostProcesses = [];
  67762. this.blurHPostProcesses = [];
  67763. this.blurVPostProcesses = [];
  67764. };
  67765. // Dispose
  67766. StandardRenderingPipeline.prototype.dispose = function () {
  67767. this._disposePostProcesses();
  67768. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67769. _super.prototype.dispose.call(this);
  67770. };
  67771. // Serialize rendering pipeline
  67772. StandardRenderingPipeline.prototype.serialize = function () {
  67773. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67774. serializationObject.customType = "StandardRenderingPipeline";
  67775. return serializationObject;
  67776. };
  67777. /**
  67778. * Static members
  67779. */
  67780. // Parse serialized pipeline
  67781. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67782. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67783. };
  67784. // Luminance steps
  67785. StandardRenderingPipeline.LuminanceSteps = 6;
  67786. __decorate([
  67787. BABYLON.serialize()
  67788. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67789. __decorate([
  67790. BABYLON.serialize()
  67791. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67792. __decorate([
  67793. BABYLON.serialize()
  67794. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67795. __decorate([
  67796. BABYLON.serialize()
  67797. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67798. __decorate([
  67799. BABYLON.serializeAsTexture("lensTexture")
  67800. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67801. __decorate([
  67802. BABYLON.serialize()
  67803. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67804. __decorate([
  67805. BABYLON.serialize()
  67806. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67807. __decorate([
  67808. BABYLON.serialize()
  67809. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67810. __decorate([
  67811. BABYLON.serialize()
  67812. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67813. __decorate([
  67814. BABYLON.serialize()
  67815. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67816. __decorate([
  67817. BABYLON.serialize()
  67818. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67819. __decorate([
  67820. BABYLON.serializeAsTexture("lensColorTexture")
  67821. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67822. __decorate([
  67823. BABYLON.serialize()
  67824. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67825. __decorate([
  67826. BABYLON.serialize()
  67827. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67828. __decorate([
  67829. BABYLON.serialize()
  67830. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67831. __decorate([
  67832. BABYLON.serialize()
  67833. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67834. __decorate([
  67835. BABYLON.serializeAsTexture("lensStarTexture")
  67836. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67837. __decorate([
  67838. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67839. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67840. __decorate([
  67841. BABYLON.serialize()
  67842. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67843. __decorate([
  67844. BABYLON.serialize()
  67845. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67846. __decorate([
  67847. BABYLON.serialize()
  67848. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67849. __decorate([
  67850. BABYLON.serialize()
  67851. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67852. __decorate([
  67853. BABYLON.serialize()
  67854. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67855. __decorate([
  67856. BABYLON.serialize()
  67857. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67858. __decorate([
  67859. BABYLON.serialize()
  67860. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67861. __decorate([
  67862. BABYLON.serialize()
  67863. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67864. __decorate([
  67865. BABYLON.serialize()
  67866. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67867. __decorate([
  67868. BABYLON.serialize()
  67869. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67870. __decorate([
  67871. BABYLON.serialize()
  67872. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67873. __decorate([
  67874. BABYLON.serialize()
  67875. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67876. return StandardRenderingPipeline;
  67877. }(BABYLON.PostProcessRenderPipeline));
  67878. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67879. })(BABYLON || (BABYLON = {}));
  67880. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67881. var BABYLON;
  67882. (function (BABYLON) {
  67883. var FxaaPostProcess = /** @class */ (function (_super) {
  67884. __extends(FxaaPostProcess, _super);
  67885. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67886. if (camera === void 0) { camera = null; }
  67887. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67888. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67889. _this.onApplyObservable.add(function (effect) {
  67890. var texelSize = _this.texelSize;
  67891. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67892. });
  67893. return _this;
  67894. }
  67895. return FxaaPostProcess;
  67896. }(BABYLON.PostProcess));
  67897. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67898. })(BABYLON || (BABYLON = {}));
  67899. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67900. var BABYLON;
  67901. (function (BABYLON) {
  67902. /**
  67903. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  67904. */
  67905. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  67906. __extends(ChromaticAberrationPostProcess, _super);
  67907. /**
  67908. * Creates a new instance of @see ChromaticAberrationPostProcess
  67909. * @param name The name of the effect.
  67910. * @param screenWidth The width of the screen to apply the effect on.
  67911. * @param screenHeight The height of the screen to apply the effect on.
  67912. * @param options The required width/height ratio to downsize to before computing the render pass.
  67913. * @param camera The camera to apply the render pass to.
  67914. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67915. * @param engine The engine which the post process will be applied. (default: current engine)
  67916. * @param reusable If the post process can be reused on the same frame. (default: false)
  67917. * @param textureType Type of textures used when performing the post process. (default: 0)
  67918. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  67919. */
  67920. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67921. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67922. if (blockCompilation === void 0) { blockCompilation = false; }
  67923. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  67924. /**
  67925. * The amount of seperation of rgb channels (default: 30)
  67926. */
  67927. _this.aberrationAmount = 30;
  67928. /**
  67929. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  67930. */
  67931. _this.radialIntensity = 0;
  67932. /**
  67933. * 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))
  67934. */
  67935. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  67936. /**
  67937. * 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))
  67938. */
  67939. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  67940. _this.onApplyObservable.add(function (effect) {
  67941. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  67942. effect.setFloat('screen_width', screenWidth);
  67943. effect.setFloat('screen_height', screenHeight);
  67944. effect.setFloat('radialIntensity', _this.radialIntensity);
  67945. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  67946. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  67947. });
  67948. return _this;
  67949. }
  67950. return ChromaticAberrationPostProcess;
  67951. }(BABYLON.PostProcess));
  67952. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  67953. })(BABYLON || (BABYLON = {}));
  67954. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  67955. var BABYLON;
  67956. (function (BABYLON) {
  67957. /**
  67958. * The SharpenPostProcess applies a sharpen kernel to every pixel
  67959. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67960. */
  67961. var SharpenPostProcess = /** @class */ (function (_super) {
  67962. __extends(SharpenPostProcess, _super);
  67963. /**
  67964. * Creates a new instance of @see ConvolutionPostProcess
  67965. * @param name The name of the effect.
  67966. * @param options The required width/height ratio to downsize to before computing the render pass.
  67967. * @param camera The camera to apply the render pass to.
  67968. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67969. * @param engine The engine which the post process will be applied. (default: current engine)
  67970. * @param reusable If the post process can be reused on the same frame. (default: false)
  67971. * @param textureType Type of textures used when performing the post process. (default: 0)
  67972. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  67973. */
  67974. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67975. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67976. if (blockCompilation === void 0) { blockCompilation = false; }
  67977. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  67978. /**
  67979. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  67980. */
  67981. _this.colorAmount = 1.0;
  67982. /**
  67983. * How much sharpness should be applied (default: 0.3)
  67984. */
  67985. _this.edgeAmount = 0.3;
  67986. _this.onApply = function (effect) {
  67987. effect.setFloat2("screenSize", _this.width, _this.height);
  67988. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  67989. };
  67990. return _this;
  67991. }
  67992. return SharpenPostProcess;
  67993. }(BABYLON.PostProcess));
  67994. BABYLON.SharpenPostProcess = SharpenPostProcess;
  67995. })(BABYLON || (BABYLON = {}));
  67996. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  67997. var BABYLON;
  67998. (function (BABYLON) {
  67999. /**
  68000. * The Blur Post Process which blurs an image based on a kernel and direction.
  68001. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68002. */
  68003. var BlurPostProcess = /** @class */ (function (_super) {
  68004. __extends(BlurPostProcess, _super);
  68005. /**
  68006. * Creates a new instance of @see BlurPostProcess
  68007. * @param name The name of the effect.
  68008. * @param direction The direction in which to blur the image.
  68009. * @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.
  68010. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68011. * @param camera The camera to apply the render pass to.
  68012. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68013. * @param engine The engine which the post process will be applied. (default: current engine)
  68014. * @param reusable If the post process can be reused on the same frame. (default: false)
  68015. * @param textureType Type of textures used when performing the post process. (default: 0)
  68016. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68017. */
  68018. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68020. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68021. if (defines === void 0) { defines = ""; }
  68022. if (blockCompilation === void 0) { blockCompilation = false; }
  68023. 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;
  68024. _this.direction = direction;
  68025. _this.blockCompilation = blockCompilation;
  68026. _this._packedFloat = false;
  68027. _this._staticDefines = "";
  68028. _this._staticDefines = defines;
  68029. _this.onApplyObservable.add(function (effect) {
  68030. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68031. });
  68032. _this.kernel = kernel;
  68033. return _this;
  68034. }
  68035. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68036. /**
  68037. * Gets the length in pixels of the blur sample region
  68038. */
  68039. get: function () {
  68040. return this._idealKernel;
  68041. },
  68042. /**
  68043. * Sets the length in pixels of the blur sample region
  68044. */
  68045. set: function (v) {
  68046. if (this._idealKernel === v) {
  68047. return;
  68048. }
  68049. v = Math.max(v, 1);
  68050. this._idealKernel = v;
  68051. this._kernel = this._nearestBestKernel(v);
  68052. if (!this.blockCompilation) {
  68053. this._updateParameters();
  68054. }
  68055. },
  68056. enumerable: true,
  68057. configurable: true
  68058. });
  68059. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68060. /**
  68061. * Gets wether or not the blur is unpacking/repacking floats
  68062. */
  68063. get: function () {
  68064. return this._packedFloat;
  68065. },
  68066. /**
  68067. * Sets wether or not the blur needs to unpack/repack floats
  68068. */
  68069. set: function (v) {
  68070. if (this._packedFloat === v) {
  68071. return;
  68072. }
  68073. this._packedFloat = v;
  68074. if (!this.blockCompilation) {
  68075. this._updateParameters();
  68076. }
  68077. },
  68078. enumerable: true,
  68079. configurable: true
  68080. });
  68081. /**
  68082. * Updates the effect with the current post process compile time values and recompiles the shader.
  68083. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68084. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68085. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68086. * @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
  68087. * @param onCompiled Called when the shader has been compiled.
  68088. * @param onError Called if there is an error when compiling a shader.
  68089. */
  68090. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68091. if (defines === void 0) { defines = null; }
  68092. if (uniforms === void 0) { uniforms = null; }
  68093. if (samplers === void 0) { samplers = null; }
  68094. this._updateParameters(onCompiled, onError);
  68095. };
  68096. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68097. // Generate sampling offsets and weights
  68098. var N = this._kernel;
  68099. var centerIndex = (N - 1) / 2;
  68100. // Generate Gaussian sampling weights over kernel
  68101. var offsets = [];
  68102. var weights = [];
  68103. var totalWeight = 0;
  68104. for (var i = 0; i < N; i++) {
  68105. var u = i / (N - 1);
  68106. var w = this._gaussianWeight(u * 2.0 - 1);
  68107. offsets[i] = (i - centerIndex);
  68108. weights[i] = w;
  68109. totalWeight += w;
  68110. }
  68111. // Normalize weights
  68112. for (var i = 0; i < weights.length; i++) {
  68113. weights[i] /= totalWeight;
  68114. }
  68115. // Optimize: combine samples to take advantage of hardware linear sampling
  68116. // Walk from left to center, combining pairs (symmetrically)
  68117. var linearSamplingWeights = [];
  68118. var linearSamplingOffsets = [];
  68119. var linearSamplingMap = [];
  68120. for (var i = 0; i <= centerIndex; i += 2) {
  68121. var j = Math.min(i + 1, Math.floor(centerIndex));
  68122. var singleCenterSample = i === j;
  68123. if (singleCenterSample) {
  68124. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68125. }
  68126. else {
  68127. var sharedCell = j === centerIndex;
  68128. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68129. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68130. if (offsetLinear === 0) {
  68131. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68132. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68133. }
  68134. else {
  68135. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68136. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68137. }
  68138. }
  68139. }
  68140. for (var i = 0; i < linearSamplingMap.length; i++) {
  68141. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68142. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68143. }
  68144. // Replace with optimized
  68145. offsets = linearSamplingOffsets;
  68146. weights = linearSamplingWeights;
  68147. // Generate shaders
  68148. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68149. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68150. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68151. var defines = "";
  68152. defines += this._staticDefines;
  68153. for (var i = 0; i < varyingCount; i++) {
  68154. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68155. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68156. }
  68157. var depCount = 0;
  68158. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68159. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68160. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68161. depCount++;
  68162. }
  68163. if (this.packedFloat) {
  68164. defines += "#define PACKEDFLOAT 1";
  68165. }
  68166. _super.prototype.updateEffect.call(this, defines, null, null, {
  68167. varyingCount: varyingCount,
  68168. depCount: depCount
  68169. }, onCompiled, onError);
  68170. };
  68171. /**
  68172. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68173. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68174. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68175. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68176. * The gaps between physical kernels are compensated for in the weighting of the samples
  68177. * @param idealKernel Ideal blur kernel.
  68178. * @return Nearest best kernel.
  68179. */
  68180. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68181. var v = Math.round(idealKernel);
  68182. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68183. var k = _a[_i];
  68184. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68185. return Math.max(k, 3);
  68186. }
  68187. }
  68188. return Math.max(v, 3);
  68189. };
  68190. /**
  68191. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68192. * @param x The point on the Gaussian distribution to sample.
  68193. * @return the value of the Gaussian function at x.
  68194. */
  68195. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68196. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68197. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68198. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68199. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68200. // truncated at around 1.3% of peak strength.
  68201. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68202. var sigma = (1 / 3);
  68203. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68204. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68205. var weight = (1.0 / denominator) * Math.exp(exponent);
  68206. return weight;
  68207. };
  68208. /**
  68209. * Generates a string that can be used as a floating point number in GLSL.
  68210. * @param x Value to print.
  68211. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68212. * @return GLSL float string.
  68213. */
  68214. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68215. if (decimalFigures === void 0) { decimalFigures = 8; }
  68216. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68217. };
  68218. return BlurPostProcess;
  68219. }(BABYLON.PostProcess));
  68220. BABYLON.BlurPostProcess = BlurPostProcess;
  68221. })(BABYLON || (BABYLON = {}));
  68222. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68223. var BABYLON;
  68224. (function (BABYLON) {
  68225. /**
  68226. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68227. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68228. * based on samples that have a large difference in distance than the center pixel.
  68229. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68230. */
  68231. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68232. __extends(DepthOfFieldBlurPostProcess, _super);
  68233. /**
  68234. * Creates a new instance of @see CircleOfConfusionPostProcess
  68235. * @param name The name of the effect.
  68236. * @param scene The scene the effect belongs to.
  68237. * @param direction The direction the blur should be applied.
  68238. * @param kernel The size of the kernel used to blur.
  68239. * @param options The required width/height ratio to downsize to before computing the render pass.
  68240. * @param camera The camera to apply the render pass to.
  68241. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68242. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68243. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68244. * @param engine The engine which the post process will be applied. (default: current engine)
  68245. * @param reusable If the post process can be reused on the same frame. (default: false)
  68246. * @param textureType Type of textures used when performing the post process. (default: 0)
  68247. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68248. */
  68249. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  68250. if (imageToBlur === void 0) { imageToBlur = null; }
  68251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68252. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68253. if (blockCompilation === void 0) { blockCompilation = false; }
  68254. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  68255. _this.direction = direction;
  68256. _this.onApplyObservable.add(function (effect) {
  68257. if (imageToBlur != null) {
  68258. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68259. }
  68260. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68261. if (scene.activeCamera) {
  68262. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68263. }
  68264. });
  68265. return _this;
  68266. }
  68267. return DepthOfFieldBlurPostProcess;
  68268. }(BABYLON.BlurPostProcess));
  68269. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68270. })(BABYLON || (BABYLON = {}));
  68271. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68272. var BABYLON;
  68273. (function (BABYLON) {
  68274. /**
  68275. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68276. */
  68277. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68278. __extends(DepthOfFieldMergePostProcess, _super);
  68279. /**
  68280. * Creates a new instance of @see CircleOfConfusionPostProcess
  68281. * @param name The name of the effect.
  68282. * @param original The non-blurred image to be modified
  68283. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68284. * @param blurSteps Incrimental bluring post processes.
  68285. * @param options The required width/height ratio to downsize to before computing the render pass.
  68286. * @param camera The camera to apply the render pass to.
  68287. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68288. * @param engine The engine which the post process will be applied. (default: current engine)
  68289. * @param reusable If the post process can be reused on the same frame. (default: false)
  68290. * @param textureType Type of textures used when performing the post process. (default: 0)
  68291. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68292. */
  68293. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68294. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68295. if (blockCompilation === void 0) { blockCompilation = false; }
  68296. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  68297. _this.blurSteps = blurSteps;
  68298. _this.onApplyObservable.add(function (effect) {
  68299. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68300. effect.setTextureFromPostProcess("originalSampler", original);
  68301. blurSteps.forEach(function (step, index) {
  68302. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68303. });
  68304. });
  68305. if (!blockCompilation) {
  68306. _this.updateEffect();
  68307. }
  68308. return _this;
  68309. }
  68310. /**
  68311. * Updates the effect with the current post process compile time values and recompiles the shader.
  68312. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68313. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68314. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68315. * @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
  68316. * @param onCompiled Called when the shader has been compiled.
  68317. * @param onError Called if there is an error when compiling a shader.
  68318. */
  68319. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68320. if (defines === void 0) { defines = null; }
  68321. if (uniforms === void 0) { uniforms = null; }
  68322. if (samplers === void 0) { samplers = null; }
  68323. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  68324. };
  68325. return DepthOfFieldMergePostProcess;
  68326. }(BABYLON.PostProcess));
  68327. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68328. })(BABYLON || (BABYLON = {}));
  68329. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68330. var BABYLON;
  68331. (function (BABYLON) {
  68332. /**
  68333. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68334. */
  68335. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68336. __extends(CircleOfConfusionPostProcess, _super);
  68337. /**
  68338. * Creates a new instance of @see CircleOfConfusionPostProcess
  68339. * @param name The name of the effect.
  68340. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  68341. * @param options The required width/height ratio to downsize to before computing the render pass.
  68342. * @param camera The camera to apply the render pass to.
  68343. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68344. * @param engine The engine which the post process will be applied. (default: current engine)
  68345. * @param reusable If the post process can be reused on the same frame. (default: false)
  68346. * @param textureType Type of textures used when performing the post process. (default: 0)
  68347. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68348. */
  68349. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68350. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68351. if (blockCompilation === void 0) { blockCompilation = false; }
  68352. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68353. /**
  68354. * 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.
  68355. */
  68356. _this.lensSize = 50;
  68357. /**
  68358. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68359. */
  68360. _this.fStop = 1.4;
  68361. /**
  68362. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68363. */
  68364. _this.focusDistance = 2000;
  68365. /**
  68366. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68367. */
  68368. _this.focalLength = 50;
  68369. _this._depthTexture = null;
  68370. _this._depthTexture = depthTexture;
  68371. _this.onApplyObservable.add(function (effect) {
  68372. if (!_this._depthTexture) {
  68373. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  68374. return;
  68375. }
  68376. effect.setTexture("depthSampler", _this._depthTexture);
  68377. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68378. var aperture = _this.lensSize / _this.fStop;
  68379. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68380. effect.setFloat('focusDistance', _this.focusDistance);
  68381. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68382. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  68383. });
  68384. return _this;
  68385. }
  68386. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  68387. /**
  68388. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  68389. */
  68390. set: function (value) {
  68391. this._depthTexture = value;
  68392. },
  68393. enumerable: true,
  68394. configurable: true
  68395. });
  68396. return CircleOfConfusionPostProcess;
  68397. }(BABYLON.PostProcess));
  68398. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68399. })(BABYLON || (BABYLON = {}));
  68400. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68401. var BABYLON;
  68402. (function (BABYLON) {
  68403. /**
  68404. * Specifies the level of max blur that should be applied when using the depth of field effect
  68405. */
  68406. var DepthOfFieldEffectBlurLevel;
  68407. (function (DepthOfFieldEffectBlurLevel) {
  68408. /**
  68409. * Subtle blur
  68410. */
  68411. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68412. /**
  68413. * Medium blur
  68414. */
  68415. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68416. /**
  68417. * Large blur
  68418. */
  68419. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68420. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68421. ;
  68422. /**
  68423. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68424. */
  68425. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68426. __extends(DepthOfFieldEffect, _super);
  68427. /**
  68428. * Creates a new instance of @see DepthOfFieldEffect
  68429. * @param scene The scene the effect belongs to.
  68430. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  68431. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68432. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68433. */
  68434. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  68435. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68436. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68437. if (blockCompilation === void 0) { blockCompilation = false; }
  68438. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68439. return _this._effects;
  68440. }, true) || this;
  68441. _this._effects = [];
  68442. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68443. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68444. // Capture circle of confusion texture
  68445. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68446. _this._depthOfFieldPass.autoClear = false;
  68447. // 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)
  68448. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68449. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68450. _this._depthOfFieldBlurY = [];
  68451. _this._depthOfFieldBlurX = [];
  68452. var blurCount = 1;
  68453. var kernelSize = 15;
  68454. switch (blurLevel) {
  68455. case DepthOfFieldEffectBlurLevel.High: {
  68456. blurCount = 3;
  68457. kernelSize = 51;
  68458. break;
  68459. }
  68460. case DepthOfFieldEffectBlurLevel.Medium: {
  68461. blurCount = 2;
  68462. kernelSize = 31;
  68463. break;
  68464. }
  68465. default: {
  68466. kernelSize = 15;
  68467. blurCount = 1;
  68468. break;
  68469. }
  68470. }
  68471. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68472. for (var i = 0; i < blurCount; i++) {
  68473. 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, blockCompilation);
  68474. blurY.autoClear = false;
  68475. 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, blockCompilation);
  68476. blurX.autoClear = false;
  68477. _this._depthOfFieldBlurY.push(blurY);
  68478. _this._depthOfFieldBlurX.push(blurX);
  68479. }
  68480. // Merge blurred images with original image based on circleOfConfusion
  68481. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68482. _this._depthOfFieldMerge.autoClear = false;
  68483. // Set all post processes on the effect.
  68484. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68485. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68486. _this._effects.push(_this._depthOfFieldBlurY[i]);
  68487. _this._effects.push(_this._depthOfFieldBlurX[i]);
  68488. }
  68489. _this._effects.push(_this._depthOfFieldMerge);
  68490. return _this;
  68491. }
  68492. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68493. get: function () {
  68494. return this._circleOfConfusion.focalLength;
  68495. },
  68496. /**
  68497. * The focal the length of the camera used in the effect
  68498. */
  68499. set: function (value) {
  68500. this._circleOfConfusion.focalLength = value;
  68501. },
  68502. enumerable: true,
  68503. configurable: true
  68504. });
  68505. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68506. get: function () {
  68507. return this._circleOfConfusion.fStop;
  68508. },
  68509. /**
  68510. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68511. */
  68512. set: function (value) {
  68513. this._circleOfConfusion.fStop = value;
  68514. },
  68515. enumerable: true,
  68516. configurable: true
  68517. });
  68518. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68519. get: function () {
  68520. return this._circleOfConfusion.focusDistance;
  68521. },
  68522. /**
  68523. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68524. */
  68525. set: function (value) {
  68526. this._circleOfConfusion.focusDistance = value;
  68527. },
  68528. enumerable: true,
  68529. configurable: true
  68530. });
  68531. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68532. get: function () {
  68533. return this._circleOfConfusion.lensSize;
  68534. },
  68535. /**
  68536. * 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.
  68537. */
  68538. set: function (value) {
  68539. this._circleOfConfusion.lensSize = value;
  68540. },
  68541. enumerable: true,
  68542. configurable: true
  68543. });
  68544. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  68545. /**
  68546. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  68547. */
  68548. set: function (value) {
  68549. this._circleOfConfusion.depthTexture = value;
  68550. },
  68551. enumerable: true,
  68552. configurable: true
  68553. });
  68554. /**
  68555. * Disposes each of the internal effects for a given camera.
  68556. * @param camera The camera to dispose the effect on.
  68557. */
  68558. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68559. this._depthOfFieldPass.dispose(camera);
  68560. this._circleOfConfusion.dispose(camera);
  68561. this._depthOfFieldBlurX.forEach(function (element) {
  68562. element.dispose(camera);
  68563. });
  68564. this._depthOfFieldBlurY.forEach(function (element) {
  68565. element.dispose(camera);
  68566. });
  68567. this._depthOfFieldMerge.dispose(camera);
  68568. };
  68569. /**
  68570. * Internal
  68571. */
  68572. DepthOfFieldEffect.prototype._updateEffects = function () {
  68573. for (var effect in this._effects) {
  68574. this._effects[effect].updateEffect();
  68575. }
  68576. };
  68577. /**
  68578. * Internal
  68579. * @returns if all the contained post processes are ready.
  68580. */
  68581. DepthOfFieldEffect.prototype._isReady = function () {
  68582. for (var effect in this._effects) {
  68583. if (!this._effects[effect].isReady()) {
  68584. return false;
  68585. }
  68586. }
  68587. return true;
  68588. };
  68589. return DepthOfFieldEffect;
  68590. }(BABYLON.PostProcessRenderEffect));
  68591. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68592. })(BABYLON || (BABYLON = {}));
  68593. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68594. var BABYLON;
  68595. (function (BABYLON) {
  68596. /**
  68597. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68598. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68599. */
  68600. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68601. __extends(DefaultRenderingPipeline, _super);
  68602. /**
  68603. * @constructor
  68604. * @param {string} name - The rendering pipeline name
  68605. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68606. * @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)
  68607. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68608. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68609. */
  68610. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68611. if (automaticBuild === void 0) { automaticBuild = true; }
  68612. var _this = _super.call(this, scene.getEngine(), name) || this;
  68613. _this._originalCameras = [];
  68614. /**
  68615. * ID of the sharpen post process,
  68616. */
  68617. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  68618. /**
  68619. * ID of the pass post process used for bloom,
  68620. */
  68621. _this.PassPostProcessId = "PassPostProcessEffect";
  68622. /**
  68623. * ID of the highlight post process used for bloom,
  68624. */
  68625. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68626. /**
  68627. * ID of the blurX post process used for bloom,
  68628. */
  68629. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68630. /**
  68631. * ID of the blurY post process used for bloom,
  68632. */
  68633. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68634. /**
  68635. * ID of the copy back post process used for bloom,
  68636. */
  68637. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68638. /**
  68639. * ID of the image processing post process;
  68640. */
  68641. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68642. /**
  68643. * ID of the Fast Approximate Anti-Aliasing post process;
  68644. */
  68645. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68646. /**
  68647. * ID of the final merge post process;
  68648. */
  68649. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68650. /**
  68651. * ID of the chromatic aberration post process,
  68652. */
  68653. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  68654. /**
  68655. * Animations which can be used to tweak settings over a period of time
  68656. */
  68657. _this.animations = [];
  68658. // Values
  68659. _this._sharpenEnabled = false;
  68660. _this._bloomEnabled = false;
  68661. _this._depthOfFieldEnabled = false;
  68662. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68663. _this._fxaaEnabled = false;
  68664. _this._msaaEnabled = false;
  68665. _this._imageProcessingEnabled = true;
  68666. _this._bloomScale = 0.6;
  68667. _this._chromaticAberrationEnabled = false;
  68668. _this._buildAllowed = true;
  68669. /**
  68670. * Specifies the size of the bloom blur kernel, relative to the final output size
  68671. */
  68672. _this.bloomKernel = 64;
  68673. /**
  68674. * Specifies the weight of the bloom in the final rendering
  68675. */
  68676. _this._bloomWeight = 0.15;
  68677. _this._prevPostProcess = null;
  68678. _this._prevPrevPostProcess = null;
  68679. _this._cameras = cameras || [];
  68680. _this._originalCameras = _this._cameras.slice();
  68681. _this._buildAllowed = automaticBuild;
  68682. // Initialize
  68683. _this._scene = scene;
  68684. var caps = _this._scene.getEngine().getCaps();
  68685. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68686. // Misc
  68687. if (_this._hdr) {
  68688. if (caps.textureHalfFloatRender) {
  68689. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68690. }
  68691. else if (caps.textureFloatRender) {
  68692. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68693. }
  68694. }
  68695. else {
  68696. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68697. }
  68698. // Attach
  68699. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68700. var engine = _this._scene.getEngine();
  68701. // Create post processes before hand so they can be modified before enabled.
  68702. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  68703. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68704. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  68705. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  68706. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68707. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  68708. _this._buildPipeline();
  68709. return _this;
  68710. }
  68711. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  68712. get: function () {
  68713. return this._sharpenEnabled;
  68714. },
  68715. /**
  68716. * Enable or disable the sharpen process from the pipeline
  68717. */
  68718. set: function (enabled) {
  68719. if (this._sharpenEnabled === enabled) {
  68720. return;
  68721. }
  68722. this._sharpenEnabled = enabled;
  68723. this._buildPipeline();
  68724. },
  68725. enumerable: true,
  68726. configurable: true
  68727. });
  68728. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68729. get: function () {
  68730. return this._bloomWeight;
  68731. },
  68732. /**
  68733. * The strength of the bloom.
  68734. */
  68735. set: function (value) {
  68736. if (this._bloomWeight === value) {
  68737. return;
  68738. }
  68739. this._bloomWeight = value;
  68740. if (this._hdr && this.copyBack) {
  68741. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68742. }
  68743. },
  68744. enumerable: true,
  68745. configurable: true
  68746. });
  68747. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68748. get: function () {
  68749. return this._bloomScale;
  68750. },
  68751. /**
  68752. * The scale of the bloom, lower value will provide better performance.
  68753. */
  68754. set: function (value) {
  68755. if (this._bloomScale === value) {
  68756. return;
  68757. }
  68758. this._bloomScale = value;
  68759. this._buildPipeline();
  68760. },
  68761. enumerable: true,
  68762. configurable: true
  68763. });
  68764. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68765. get: function () {
  68766. return this._bloomEnabled;
  68767. },
  68768. /**
  68769. * Enable or disable the bloom from the pipeline
  68770. */
  68771. set: function (enabled) {
  68772. if (this._bloomEnabled === enabled) {
  68773. return;
  68774. }
  68775. this._bloomEnabled = enabled;
  68776. this._buildPipeline();
  68777. },
  68778. enumerable: true,
  68779. configurable: true
  68780. });
  68781. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68782. /**
  68783. * If the depth of field is enabled.
  68784. */
  68785. get: function () {
  68786. return this._depthOfFieldEnabled;
  68787. },
  68788. set: function (enabled) {
  68789. if (this._depthOfFieldEnabled === enabled) {
  68790. return;
  68791. }
  68792. this._depthOfFieldEnabled = enabled;
  68793. this._buildPipeline();
  68794. },
  68795. enumerable: true,
  68796. configurable: true
  68797. });
  68798. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68799. /**
  68800. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68801. */
  68802. get: function () {
  68803. return this._depthOfFieldBlurLevel;
  68804. },
  68805. set: function (value) {
  68806. if (this._depthOfFieldBlurLevel === value) {
  68807. return;
  68808. }
  68809. this._depthOfFieldBlurLevel = value;
  68810. // recreate dof and dispose old as this setting is not dynamic
  68811. var oldDof = this.depthOfField;
  68812. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68813. this.depthOfField.focalLength = oldDof.focalLength;
  68814. this.depthOfField.focusDistance = oldDof.focusDistance;
  68815. this.depthOfField.fStop = oldDof.fStop;
  68816. this.depthOfField.lensSize = oldDof.lensSize;
  68817. for (var i = 0; i < this._cameras.length; i++) {
  68818. oldDof.disposeEffects(this._cameras[i]);
  68819. }
  68820. this._buildPipeline();
  68821. },
  68822. enumerable: true,
  68823. configurable: true
  68824. });
  68825. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68826. get: function () {
  68827. return this._fxaaEnabled;
  68828. },
  68829. /**
  68830. * If the anti aliasing is enabled.
  68831. */
  68832. set: function (enabled) {
  68833. if (this._fxaaEnabled === enabled) {
  68834. return;
  68835. }
  68836. this._fxaaEnabled = enabled;
  68837. this._buildPipeline();
  68838. },
  68839. enumerable: true,
  68840. configurable: true
  68841. });
  68842. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68843. get: function () {
  68844. return this._msaaEnabled;
  68845. },
  68846. /**
  68847. * If the multisample anti-aliasing is enabled.
  68848. */
  68849. set: function (enabled) {
  68850. if (this._msaaEnabled === enabled) {
  68851. return;
  68852. }
  68853. this._msaaEnabled = enabled;
  68854. this._buildPipeline();
  68855. },
  68856. enumerable: true,
  68857. configurable: true
  68858. });
  68859. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68860. get: function () {
  68861. return this._imageProcessingEnabled;
  68862. },
  68863. /**
  68864. * If image processing is enabled.
  68865. */
  68866. set: function (enabled) {
  68867. if (this._imageProcessingEnabled === enabled) {
  68868. return;
  68869. }
  68870. this._imageProcessingEnabled = enabled;
  68871. this._buildPipeline();
  68872. },
  68873. enumerable: true,
  68874. configurable: true
  68875. });
  68876. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68877. get: function () {
  68878. return this._chromaticAberrationEnabled;
  68879. },
  68880. /**
  68881. * Enable or disable the chromaticAberration process from the pipeline
  68882. */
  68883. set: function (enabled) {
  68884. if (this._chromaticAberrationEnabled === enabled) {
  68885. return;
  68886. }
  68887. this._chromaticAberrationEnabled = enabled;
  68888. this._buildPipeline();
  68889. },
  68890. enumerable: true,
  68891. configurable: true
  68892. });
  68893. /**
  68894. * Force the compilation of the entire pipeline.
  68895. */
  68896. DefaultRenderingPipeline.prototype.prepare = function () {
  68897. var previousState = this._buildAllowed;
  68898. this._buildAllowed = true;
  68899. this._buildPipeline();
  68900. this._buildAllowed = previousState;
  68901. };
  68902. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  68903. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  68904. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  68905. postProcess.autoClear = false;
  68906. }
  68907. else {
  68908. postProcess.autoClear = true;
  68909. }
  68910. if (!skipTextureSharing) {
  68911. if (this._prevPrevPostProcess) {
  68912. postProcess.shareOutputWith(this._prevPrevPostProcess);
  68913. }
  68914. else {
  68915. postProcess.useOwnOutput();
  68916. }
  68917. if (this._prevPostProcess) {
  68918. this._prevPrevPostProcess = this._prevPostProcess;
  68919. }
  68920. this._prevPostProcess = postProcess;
  68921. }
  68922. };
  68923. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68924. var _this = this;
  68925. if (!this._buildAllowed) {
  68926. return;
  68927. }
  68928. var engine = this._scene.getEngine();
  68929. this._disposePostProcesses();
  68930. if (this._cameras !== null) {
  68931. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68932. // get back cameras to be used to reattach pipeline
  68933. this._cameras = this._originalCameras.slice();
  68934. }
  68935. this._reset();
  68936. this._prevPostProcess = null;
  68937. this._prevPrevPostProcess = null;
  68938. if (this.sharpenEnabled) {
  68939. if (!this.sharpen.isReady()) {
  68940. this.sharpen.updateEffect();
  68941. }
  68942. this.addEffect(this._sharpenEffect);
  68943. this._setAutoClearAndTextureSharing(this.sharpen);
  68944. }
  68945. if (this.depthOfFieldEnabled) {
  68946. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68947. this.depthOfField.depthTexture = depthTexture;
  68948. if (!this.depthOfField._isReady()) {
  68949. this.depthOfField._updateEffects();
  68950. }
  68951. this.addEffect(this.depthOfField);
  68952. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  68953. }
  68954. if (this.bloomEnabled) {
  68955. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68956. this._setAutoClearAndTextureSharing(this.pass, true);
  68957. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68958. if (!this._hdr) {
  68959. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68960. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68961. this.highlights.autoClear = false;
  68962. this.highlights.alwaysForcePOT = true;
  68963. }
  68964. 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);
  68965. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68966. this.blurX.alwaysForcePOT = true;
  68967. this.blurX.autoClear = false;
  68968. this.blurX.onActivateObservable.add(function () {
  68969. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68970. _this.blurX.kernel = _this.bloomKernel * dw;
  68971. });
  68972. 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);
  68973. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68974. this.blurY.alwaysForcePOT = true;
  68975. this.blurY.autoClear = false;
  68976. this.blurY.onActivateObservable.add(function () {
  68977. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68978. _this.blurY.kernel = _this.bloomKernel * dh;
  68979. });
  68980. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68981. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68982. this.copyBack.alwaysForcePOT = true;
  68983. if (this._hdr) {
  68984. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68985. var w = this.bloomWeight;
  68986. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68987. }
  68988. else {
  68989. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68990. }
  68991. this.copyBack.autoClear = false;
  68992. }
  68993. if (this._imageProcessingEnabled) {
  68994. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68995. if (this._hdr) {
  68996. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68997. }
  68998. else {
  68999. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69000. }
  69001. }
  69002. if (this._hdr && this.imageProcessing) {
  69003. this.finalMerge = this.imageProcessing;
  69004. }
  69005. else {
  69006. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69007. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69008. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69009. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69010. }
  69011. if (this.bloomEnabled) {
  69012. if (this._hdr) {
  69013. this.copyBack.shareOutputWith(this.blurX);
  69014. if (this.imageProcessing) {
  69015. this.imageProcessing.shareOutputWith(this.pass);
  69016. this.imageProcessing.autoClear = false;
  69017. }
  69018. else {
  69019. this.finalMerge.shareOutputWith(this.pass);
  69020. }
  69021. }
  69022. else {
  69023. this.finalMerge.shareOutputWith(this.pass);
  69024. }
  69025. }
  69026. if (this.fxaaEnabled) {
  69027. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69028. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69029. this._setAutoClearAndTextureSharing(this.fxaa);
  69030. }
  69031. if (this.chromaticAberrationEnabled) {
  69032. if (!this.chromaticAberration.isReady()) {
  69033. this.chromaticAberration.updateEffect();
  69034. }
  69035. this.addEffect(this._chromaticAberrationEffect);
  69036. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69037. }
  69038. if (this._cameras !== null) {
  69039. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69040. }
  69041. if (this.msaaEnabled) {
  69042. if (!this._enableMSAAOnFirstPostProcess()) {
  69043. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69044. }
  69045. }
  69046. };
  69047. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69048. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69049. for (var i = 0; i < this._cameras.length; i++) {
  69050. var camera = this._cameras[i];
  69051. if (this.pass) {
  69052. this.pass.dispose(camera);
  69053. }
  69054. if (this.highlights) {
  69055. this.highlights.dispose(camera);
  69056. }
  69057. if (this.blurX) {
  69058. this.blurX.dispose(camera);
  69059. }
  69060. if (this.blurY) {
  69061. this.blurY.dispose(camera);
  69062. }
  69063. if (this.copyBack) {
  69064. this.copyBack.dispose(camera);
  69065. }
  69066. if (this.imageProcessing) {
  69067. this.imageProcessing.dispose(camera);
  69068. }
  69069. if (this.fxaa) {
  69070. this.fxaa.dispose(camera);
  69071. }
  69072. if (this.finalMerge) {
  69073. this.finalMerge.dispose(camera);
  69074. }
  69075. // These are created in the constructor and should not be disposed on every pipeline change
  69076. if (disposeNonRecreated) {
  69077. if (this.sharpen) {
  69078. this.sharpen.dispose(camera);
  69079. }
  69080. if (this.depthOfField) {
  69081. this.depthOfField.disposeEffects(camera);
  69082. }
  69083. if (this.chromaticAberration) {
  69084. this.chromaticAberration.dispose(camera);
  69085. }
  69086. }
  69087. }
  69088. this.pass = null;
  69089. this.highlights = null;
  69090. this.blurX = null;
  69091. this.blurY = null;
  69092. this.copyBack = null;
  69093. this.imageProcessing = null;
  69094. this.fxaa = null;
  69095. this.finalMerge = null;
  69096. if (disposeNonRecreated) {
  69097. this.sharpen = null;
  69098. this.depthOfField = null;
  69099. this.chromaticAberration = null;
  69100. }
  69101. };
  69102. /**
  69103. * Dispose of the pipeline and stop all post processes
  69104. */
  69105. DefaultRenderingPipeline.prototype.dispose = function () {
  69106. this._disposePostProcesses(true);
  69107. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69108. _super.prototype.dispose.call(this);
  69109. };
  69110. /**
  69111. * Serialize the rendering pipeline (Used when exporting)
  69112. * @returns the serialized object
  69113. */
  69114. DefaultRenderingPipeline.prototype.serialize = function () {
  69115. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69116. serializationObject.customType = "DefaultRenderingPipeline";
  69117. return serializationObject;
  69118. };
  69119. /**
  69120. * Parse the serialized pipeline
  69121. * @param source Source pipeline.
  69122. * @param scene The scene to load the pipeline to.
  69123. * @param rootUrl The URL of the serialized pipeline.
  69124. * @returns An instantiated pipeline from the serialized object.
  69125. */
  69126. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69127. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69128. };
  69129. __decorate([
  69130. BABYLON.serialize()
  69131. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69132. __decorate([
  69133. BABYLON.serialize()
  69134. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69135. __decorate([
  69136. BABYLON.serialize()
  69137. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69138. __decorate([
  69139. BABYLON.serialize()
  69140. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69141. __decorate([
  69142. BABYLON.serialize()
  69143. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69144. __decorate([
  69145. BABYLON.serialize()
  69146. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69147. __decorate([
  69148. BABYLON.serialize()
  69149. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69150. __decorate([
  69151. BABYLON.serialize()
  69152. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69153. __decorate([
  69154. BABYLON.serialize()
  69155. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69156. __decorate([
  69157. BABYLON.serialize()
  69158. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69159. __decorate([
  69160. BABYLON.serialize()
  69161. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69162. __decorate([
  69163. BABYLON.serialize()
  69164. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69165. __decorate([
  69166. BABYLON.serialize()
  69167. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69168. return DefaultRenderingPipeline;
  69169. }(BABYLON.PostProcessRenderPipeline));
  69170. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69171. })(BABYLON || (BABYLON = {}));
  69172. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69173. var BABYLON;
  69174. (function (BABYLON) {
  69175. /**
  69176. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69177. */
  69178. var GeometryBufferRenderer = /** @class */ (function () {
  69179. /**
  69180. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69181. * @param scene The scene the buffer belongs to
  69182. * @param ratio How big is the buffer related to the main canvas.
  69183. */
  69184. function GeometryBufferRenderer(scene, ratio) {
  69185. if (ratio === void 0) { ratio = 1; }
  69186. this._enablePosition = false;
  69187. this._scene = scene;
  69188. this._ratio = ratio;
  69189. // Render target
  69190. this._createRenderTargets();
  69191. }
  69192. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69193. /**
  69194. * Set the render list (meshes to be rendered) used in the G buffer.
  69195. */
  69196. set: function (meshes) {
  69197. this._multiRenderTarget.renderList = meshes;
  69198. },
  69199. enumerable: true,
  69200. configurable: true
  69201. });
  69202. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69203. /**
  69204. * Gets wether or not G buffer are supported by the running hardware.
  69205. * This requires draw buffer supports
  69206. */
  69207. get: function () {
  69208. return this._multiRenderTarget.isSupported;
  69209. },
  69210. enumerable: true,
  69211. configurable: true
  69212. });
  69213. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69214. /**
  69215. * Gets wether or not position are enabled for the G buffer.
  69216. */
  69217. get: function () {
  69218. return this._enablePosition;
  69219. },
  69220. /**
  69221. * Sets wether or not position are enabled for the G buffer.
  69222. */
  69223. set: function (enable) {
  69224. this._enablePosition = enable;
  69225. this.dispose();
  69226. this._createRenderTargets();
  69227. },
  69228. enumerable: true,
  69229. configurable: true
  69230. });
  69231. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69232. /**
  69233. * Gets the scene associated with the buffer.
  69234. */
  69235. get: function () {
  69236. return this._scene;
  69237. },
  69238. enumerable: true,
  69239. configurable: true
  69240. });
  69241. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69242. /**
  69243. * Gets the ratio used by the buffer during its creation.
  69244. * How big is the buffer related to the main canvas.
  69245. */
  69246. get: function () {
  69247. return this._ratio;
  69248. },
  69249. enumerable: true,
  69250. configurable: true
  69251. });
  69252. /**
  69253. * Checks wether everything is ready to render a submesh to the G buffer.
  69254. * @param subMesh the submesh to check readiness for
  69255. * @param useInstances is the mesh drawn using instance or not
  69256. * @returns true if ready otherwise false
  69257. */
  69258. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69259. var material = subMesh.getMaterial();
  69260. if (material && material.disableDepthWrite) {
  69261. return false;
  69262. }
  69263. var defines = [];
  69264. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69265. var mesh = subMesh.getMesh();
  69266. // Alpha test
  69267. if (material && material.needAlphaTesting()) {
  69268. defines.push("#define ALPHATEST");
  69269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69270. attribs.push(BABYLON.VertexBuffer.UVKind);
  69271. defines.push("#define UV1");
  69272. }
  69273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69275. defines.push("#define UV2");
  69276. }
  69277. }
  69278. // Buffers
  69279. if (this._enablePosition) {
  69280. defines.push("#define POSITION");
  69281. }
  69282. // Bones
  69283. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69284. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69285. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69286. if (mesh.numBoneInfluencers > 4) {
  69287. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69288. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69289. }
  69290. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69291. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69292. }
  69293. else {
  69294. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69295. }
  69296. // Instances
  69297. if (useInstances) {
  69298. defines.push("#define INSTANCES");
  69299. attribs.push("world0");
  69300. attribs.push("world1");
  69301. attribs.push("world2");
  69302. attribs.push("world3");
  69303. }
  69304. // Get correct effect
  69305. var join = defines.join("\n");
  69306. if (this._cachedDefines !== join) {
  69307. this._cachedDefines = join;
  69308. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69309. }
  69310. return this._effect.isReady();
  69311. };
  69312. /**
  69313. * Gets the current underlying G Buffer.
  69314. * @returns the buffer
  69315. */
  69316. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69317. return this._multiRenderTarget;
  69318. };
  69319. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69320. /**
  69321. * Gets the number of samples used to render the buffer (anti aliasing).
  69322. */
  69323. get: function () {
  69324. return this._multiRenderTarget.samples;
  69325. },
  69326. /**
  69327. * Sets the number of samples used to render the buffer (anti aliasing).
  69328. */
  69329. set: function (value) {
  69330. this._multiRenderTarget.samples = value;
  69331. },
  69332. enumerable: true,
  69333. configurable: true
  69334. });
  69335. /**
  69336. * Disposes the renderer and frees up associated resources.
  69337. */
  69338. GeometryBufferRenderer.prototype.dispose = function () {
  69339. this.getGBuffer().dispose();
  69340. };
  69341. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69342. var _this = this;
  69343. var engine = this._scene.getEngine();
  69344. var count = this._enablePosition ? 3 : 2;
  69345. 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 });
  69346. if (!this.isSupported) {
  69347. return;
  69348. }
  69349. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69350. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69351. this._multiRenderTarget.refreshRate = 1;
  69352. this._multiRenderTarget.renderParticles = false;
  69353. this._multiRenderTarget.renderList = null;
  69354. // set default depth value to 1.0 (far away)
  69355. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69356. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69357. });
  69358. // Custom render function
  69359. var renderSubMesh = function (subMesh) {
  69360. var mesh = subMesh.getRenderingMesh();
  69361. var scene = _this._scene;
  69362. var engine = scene.getEngine();
  69363. var material = subMesh.getMaterial();
  69364. if (!material) {
  69365. return;
  69366. }
  69367. // Culling
  69368. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69369. // Managing instances
  69370. var batch = mesh._getInstancesRenderList(subMesh._id);
  69371. if (batch.mustReturn) {
  69372. return;
  69373. }
  69374. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69375. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69376. engine.enableEffect(_this._effect);
  69377. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69378. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69379. _this._effect.setMatrix("view", scene.getViewMatrix());
  69380. // Alpha test
  69381. if (material && material.needAlphaTesting()) {
  69382. var alphaTexture = material.getAlphaTestTexture();
  69383. if (alphaTexture) {
  69384. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69385. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69386. }
  69387. }
  69388. // Bones
  69389. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69390. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69391. }
  69392. // Draw
  69393. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69394. }
  69395. };
  69396. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69397. var index;
  69398. if (depthOnlySubMeshes.length) {
  69399. engine.setColorWrite(false);
  69400. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69401. renderSubMesh(depthOnlySubMeshes.data[index]);
  69402. }
  69403. engine.setColorWrite(true);
  69404. }
  69405. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69406. renderSubMesh(opaqueSubMeshes.data[index]);
  69407. }
  69408. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69409. renderSubMesh(alphaTestSubMeshes.data[index]);
  69410. }
  69411. };
  69412. };
  69413. return GeometryBufferRenderer;
  69414. }());
  69415. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69416. })(BABYLON || (BABYLON = {}));
  69417. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69418. var BABYLON;
  69419. (function (BABYLON) {
  69420. var RefractionPostProcess = /** @class */ (function (_super) {
  69421. __extends(RefractionPostProcess, _super);
  69422. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69423. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69424. _this.color = color;
  69425. _this.depth = depth;
  69426. _this.colorLevel = colorLevel;
  69427. _this._ownRefractionTexture = true;
  69428. _this.onActivateObservable.add(function (cam) {
  69429. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69430. });
  69431. _this.onApplyObservable.add(function (effect) {
  69432. effect.setColor3("baseColor", _this.color);
  69433. effect.setFloat("depth", _this.depth);
  69434. effect.setFloat("colorLevel", _this.colorLevel);
  69435. effect.setTexture("refractionSampler", _this._refTexture);
  69436. });
  69437. return _this;
  69438. }
  69439. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69440. /**
  69441. * Gets or sets the refraction texture
  69442. * Please note that you are responsible for disposing the texture if you set it manually
  69443. */
  69444. get: function () {
  69445. return this._refTexture;
  69446. },
  69447. set: function (value) {
  69448. if (this._refTexture && this._ownRefractionTexture) {
  69449. this._refTexture.dispose();
  69450. }
  69451. this._refTexture = value;
  69452. this._ownRefractionTexture = false;
  69453. },
  69454. enumerable: true,
  69455. configurable: true
  69456. });
  69457. // Methods
  69458. RefractionPostProcess.prototype.dispose = function (camera) {
  69459. if (this._refTexture && this._ownRefractionTexture) {
  69460. this._refTexture.dispose();
  69461. this._refTexture = null;
  69462. }
  69463. _super.prototype.dispose.call(this, camera);
  69464. };
  69465. return RefractionPostProcess;
  69466. }(BABYLON.PostProcess));
  69467. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69468. })(BABYLON || (BABYLON = {}));
  69469. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69470. var BABYLON;
  69471. (function (BABYLON) {
  69472. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69473. __extends(BlackAndWhitePostProcess, _super);
  69474. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69475. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69476. _this.degree = 1;
  69477. _this.onApplyObservable.add(function (effect) {
  69478. effect.setFloat("degree", _this.degree);
  69479. });
  69480. return _this;
  69481. }
  69482. return BlackAndWhitePostProcess;
  69483. }(BABYLON.PostProcess));
  69484. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69485. })(BABYLON || (BABYLON = {}));
  69486. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69487. var BABYLON;
  69488. (function (BABYLON) {
  69489. /**
  69490. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  69491. * input texture to perform effects such as edge detection or sharpening
  69492. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69493. */
  69494. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69495. __extends(ConvolutionPostProcess, _super);
  69496. /**
  69497. * Creates a new instance of @see ConvolutionPostProcess
  69498. * @param name The name of the effect.
  69499. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  69500. * @param options The required width/height ratio to downsize to before computing the render pass.
  69501. * @param camera The camera to apply the render pass to.
  69502. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69503. * @param engine The engine which the post process will be applied. (default: current engine)
  69504. * @param reusable If the post process can be reused on the same frame. (default: false)
  69505. * @param textureType Type of textures used when performing the post process. (default: 0)
  69506. */
  69507. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  69508. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69509. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69510. _this.kernel = kernel;
  69511. _this.onApply = function (effect) {
  69512. effect.setFloat2("screenSize", _this.width, _this.height);
  69513. effect.setArray("kernel", _this.kernel);
  69514. };
  69515. return _this;
  69516. }
  69517. // Statics
  69518. /**
  69519. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69520. */
  69521. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69522. /**
  69523. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69524. */
  69525. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69526. /**
  69527. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69528. */
  69529. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69530. /**
  69531. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69532. */
  69533. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69534. /**
  69535. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69536. */
  69537. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69538. /**
  69539. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69540. */
  69541. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69542. return ConvolutionPostProcess;
  69543. }(BABYLON.PostProcess));
  69544. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69545. })(BABYLON || (BABYLON = {}));
  69546. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69547. var BABYLON;
  69548. (function (BABYLON) {
  69549. var FilterPostProcess = /** @class */ (function (_super) {
  69550. __extends(FilterPostProcess, _super);
  69551. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69552. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69553. _this.kernelMatrix = kernelMatrix;
  69554. _this.onApply = function (effect) {
  69555. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69556. };
  69557. return _this;
  69558. }
  69559. return FilterPostProcess;
  69560. }(BABYLON.PostProcess));
  69561. BABYLON.FilterPostProcess = FilterPostProcess;
  69562. })(BABYLON || (BABYLON = {}));
  69563. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69564. var BABYLON;
  69565. (function (BABYLON) {
  69566. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69567. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69568. __extends(VolumetricLightScatteringPostProcess, _super);
  69569. /**
  69570. * @constructor
  69571. * @param {string} name - The post-process name
  69572. * @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)
  69573. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69574. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69575. * @param {number} samples - The post-process quality, default 100
  69576. * @param {number} samplingMode - The post-process filtering mode
  69577. * @param {BABYLON.Engine} engine - The babylon engine
  69578. * @param {boolean} reusable - If the post-process is reusable
  69579. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69580. */
  69581. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69582. if (samples === void 0) { samples = 100; }
  69583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69584. 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;
  69585. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69586. /**
  69587. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69588. * @type {Vector3}
  69589. */
  69590. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69591. /**
  69592. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69593. * @type {boolean}
  69594. */
  69595. _this.useCustomMeshPosition = false;
  69596. /**
  69597. * If the post-process should inverse the light scattering direction
  69598. * @type {boolean}
  69599. */
  69600. _this.invert = true;
  69601. /**
  69602. * Array containing the excluded meshes not rendered in the internal pass
  69603. */
  69604. _this.excludedMeshes = new Array();
  69605. /**
  69606. * Controls the overall intensity of the post-process
  69607. * @type {number}
  69608. */
  69609. _this.exposure = 0.3;
  69610. /**
  69611. * Dissipates each sample's contribution in range [0, 1]
  69612. * @type {number}
  69613. */
  69614. _this.decay = 0.96815;
  69615. /**
  69616. * Controls the overall intensity of each sample
  69617. * @type {number}
  69618. */
  69619. _this.weight = 0.58767;
  69620. /**
  69621. * Controls the density of each sample
  69622. * @type {number}
  69623. */
  69624. _this.density = 0.926;
  69625. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69626. engine = scene.getEngine();
  69627. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69628. // Configure mesh
  69629. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69630. // Configure
  69631. _this._createPass(scene, ratio.passRatio || ratio);
  69632. _this.onActivate = function (camera) {
  69633. if (!_this.isSupported) {
  69634. _this.dispose(camera);
  69635. }
  69636. _this.onActivate = null;
  69637. };
  69638. _this.onApplyObservable.add(function (effect) {
  69639. _this._updateMeshScreenCoordinates(scene);
  69640. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69641. effect.setFloat("exposure", _this.exposure);
  69642. effect.setFloat("decay", _this.decay);
  69643. effect.setFloat("weight", _this.weight);
  69644. effect.setFloat("density", _this.density);
  69645. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69646. });
  69647. return _this;
  69648. }
  69649. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69650. get: function () {
  69651. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69652. return false;
  69653. },
  69654. set: function (useDiffuseColor) {
  69655. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69656. },
  69657. enumerable: true,
  69658. configurable: true
  69659. });
  69660. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69661. return "VolumetricLightScatteringPostProcess";
  69662. };
  69663. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69664. var mesh = subMesh.getMesh();
  69665. // Render this.mesh as default
  69666. if (mesh === this.mesh && mesh.material) {
  69667. return mesh.material.isReady(mesh);
  69668. }
  69669. var defines = [];
  69670. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69671. var material = subMesh.getMaterial();
  69672. // Alpha test
  69673. if (material) {
  69674. if (material.needAlphaTesting()) {
  69675. defines.push("#define ALPHATEST");
  69676. }
  69677. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69678. attribs.push(BABYLON.VertexBuffer.UVKind);
  69679. defines.push("#define UV1");
  69680. }
  69681. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69682. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69683. defines.push("#define UV2");
  69684. }
  69685. }
  69686. // Bones
  69687. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69690. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69691. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69692. }
  69693. else {
  69694. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69695. }
  69696. // Instances
  69697. if (useInstances) {
  69698. defines.push("#define INSTANCES");
  69699. attribs.push("world0");
  69700. attribs.push("world1");
  69701. attribs.push("world2");
  69702. attribs.push("world3");
  69703. }
  69704. // Get correct effect
  69705. var join = defines.join("\n");
  69706. if (this._cachedDefines !== join) {
  69707. this._cachedDefines = join;
  69708. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69709. }
  69710. return this._volumetricLightScatteringPass.isReady();
  69711. };
  69712. /**
  69713. * Sets the new light position for light scattering effect
  69714. * @param {BABYLON.Vector3} The new custom light position
  69715. */
  69716. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69717. this.customMeshPosition = position;
  69718. };
  69719. /**
  69720. * Returns the light position for light scattering effect
  69721. * @return {BABYLON.Vector3} The custom light position
  69722. */
  69723. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69724. return this.customMeshPosition;
  69725. };
  69726. /**
  69727. * Disposes the internal assets and detaches the post-process from the camera
  69728. */
  69729. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69730. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69731. if (rttIndex !== -1) {
  69732. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69733. }
  69734. this._volumetricLightScatteringRTT.dispose();
  69735. _super.prototype.dispose.call(this, camera);
  69736. };
  69737. /**
  69738. * Returns the render target texture used by the post-process
  69739. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69740. */
  69741. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69742. return this._volumetricLightScatteringRTT;
  69743. };
  69744. // Private methods
  69745. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69746. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69747. return true;
  69748. }
  69749. return false;
  69750. };
  69751. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69752. var _this = this;
  69753. var engine = scene.getEngine();
  69754. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69755. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69756. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69757. this._volumetricLightScatteringRTT.renderList = null;
  69758. this._volumetricLightScatteringRTT.renderParticles = false;
  69759. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69760. var camera = this.getCamera();
  69761. if (camera) {
  69762. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69763. }
  69764. else {
  69765. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69766. }
  69767. // Custom render function for submeshes
  69768. var renderSubMesh = function (subMesh) {
  69769. var mesh = subMesh.getRenderingMesh();
  69770. if (_this._meshExcluded(mesh)) {
  69771. return;
  69772. }
  69773. var material = subMesh.getMaterial();
  69774. if (!material) {
  69775. return;
  69776. }
  69777. var scene = mesh.getScene();
  69778. var engine = scene.getEngine();
  69779. // Culling
  69780. engine.setState(material.backFaceCulling);
  69781. // Managing instances
  69782. var batch = mesh._getInstancesRenderList(subMesh._id);
  69783. if (batch.mustReturn) {
  69784. return;
  69785. }
  69786. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69787. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69788. var effect = _this._volumetricLightScatteringPass;
  69789. if (mesh === _this.mesh) {
  69790. if (subMesh.effect) {
  69791. effect = subMesh.effect;
  69792. }
  69793. else {
  69794. effect = material.getEffect();
  69795. }
  69796. }
  69797. engine.enableEffect(effect);
  69798. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69799. if (mesh === _this.mesh) {
  69800. material.bind(mesh.getWorldMatrix(), mesh);
  69801. }
  69802. else {
  69803. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69804. // Alpha test
  69805. if (material && material.needAlphaTesting()) {
  69806. var alphaTexture = material.getAlphaTestTexture();
  69807. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69808. if (alphaTexture) {
  69809. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69810. }
  69811. }
  69812. // Bones
  69813. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69814. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69815. }
  69816. }
  69817. // Draw
  69818. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69819. }
  69820. };
  69821. // Render target texture callbacks
  69822. var savedSceneClearColor;
  69823. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69824. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69825. savedSceneClearColor = scene.clearColor;
  69826. scene.clearColor = sceneClearColor;
  69827. });
  69828. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69829. scene.clearColor = savedSceneClearColor;
  69830. });
  69831. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69832. var engine = scene.getEngine();
  69833. var index;
  69834. if (depthOnlySubMeshes.length) {
  69835. engine.setColorWrite(false);
  69836. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69837. renderSubMesh(depthOnlySubMeshes.data[index]);
  69838. }
  69839. engine.setColorWrite(true);
  69840. }
  69841. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69842. renderSubMesh(opaqueSubMeshes.data[index]);
  69843. }
  69844. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69845. renderSubMesh(alphaTestSubMeshes.data[index]);
  69846. }
  69847. if (transparentSubMeshes.length) {
  69848. // Sort sub meshes
  69849. for (index = 0; index < transparentSubMeshes.length; index++) {
  69850. var submesh = transparentSubMeshes.data[index];
  69851. var boundingInfo = submesh.getBoundingInfo();
  69852. if (boundingInfo && scene.activeCamera) {
  69853. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69854. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69855. }
  69856. }
  69857. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69858. sortedArray.sort(function (a, b) {
  69859. // Alpha index first
  69860. if (a._alphaIndex > b._alphaIndex) {
  69861. return 1;
  69862. }
  69863. if (a._alphaIndex < b._alphaIndex) {
  69864. return -1;
  69865. }
  69866. // Then distance to camera
  69867. if (a._distanceToCamera < b._distanceToCamera) {
  69868. return 1;
  69869. }
  69870. if (a._distanceToCamera > b._distanceToCamera) {
  69871. return -1;
  69872. }
  69873. return 0;
  69874. });
  69875. // Render sub meshes
  69876. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69877. for (index = 0; index < sortedArray.length; index++) {
  69878. renderSubMesh(sortedArray[index]);
  69879. }
  69880. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69881. }
  69882. };
  69883. };
  69884. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69885. var transform = scene.getTransformMatrix();
  69886. var meshPosition;
  69887. if (this.useCustomMeshPosition) {
  69888. meshPosition = this.customMeshPosition;
  69889. }
  69890. else if (this.attachedNode) {
  69891. meshPosition = this.attachedNode.position;
  69892. }
  69893. else {
  69894. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69895. }
  69896. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69897. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69898. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69899. if (this.invert)
  69900. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69901. };
  69902. // Static methods
  69903. /**
  69904. * Creates a default mesh for the Volumeric Light Scattering post-process
  69905. * @param {string} The mesh name
  69906. * @param {BABYLON.Scene} The scene where to create the mesh
  69907. * @return {BABYLON.Mesh} the default mesh
  69908. */
  69909. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69910. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69911. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69912. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69913. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69914. mesh.material = material;
  69915. return mesh;
  69916. };
  69917. __decorate([
  69918. BABYLON.serializeAsVector3()
  69919. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69920. __decorate([
  69921. BABYLON.serialize()
  69922. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69923. __decorate([
  69924. BABYLON.serialize()
  69925. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69926. __decorate([
  69927. BABYLON.serializeAsMeshReference()
  69928. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69929. __decorate([
  69930. BABYLON.serialize()
  69931. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69932. __decorate([
  69933. BABYLON.serialize()
  69934. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69935. __decorate([
  69936. BABYLON.serialize()
  69937. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69938. __decorate([
  69939. BABYLON.serialize()
  69940. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69941. __decorate([
  69942. BABYLON.serialize()
  69943. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69944. return VolumetricLightScatteringPostProcess;
  69945. }(BABYLON.PostProcess));
  69946. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69947. })(BABYLON || (BABYLON = {}));
  69948. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69949. //
  69950. // This post-process allows the modification of rendered colors by using
  69951. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69952. //
  69953. // The object needs to be provided an url to a texture containing the color
  69954. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69955. // Use an image editing software to tweak the LUT to match your needs.
  69956. //
  69957. // For an example of a color LUT, see here:
  69958. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69959. // For explanations on color grading, see here:
  69960. // http://udn.epicgames.com/Three/ColorGrading.html
  69961. //
  69962. var BABYLON;
  69963. (function (BABYLON) {
  69964. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69965. __extends(ColorCorrectionPostProcess, _super);
  69966. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69967. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69968. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69969. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69970. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69971. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69972. _this.onApply = function (effect) {
  69973. effect.setTexture("colorTable", _this._colorTableTexture);
  69974. };
  69975. return _this;
  69976. }
  69977. return ColorCorrectionPostProcess;
  69978. }(BABYLON.PostProcess));
  69979. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69980. })(BABYLON || (BABYLON = {}));
  69981. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69982. var BABYLON;
  69983. (function (BABYLON) {
  69984. var TonemappingOperator;
  69985. (function (TonemappingOperator) {
  69986. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69987. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69988. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69989. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69990. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69991. ;
  69992. var TonemapPostProcess = /** @class */ (function (_super) {
  69993. __extends(TonemapPostProcess, _super);
  69994. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69995. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69996. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69997. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69998. _this._operator = _operator;
  69999. _this.exposureAdjustment = exposureAdjustment;
  70000. var defines = "#define ";
  70001. if (_this._operator === TonemappingOperator.Hable)
  70002. defines += "HABLE_TONEMAPPING";
  70003. else if (_this._operator === TonemappingOperator.Reinhard)
  70004. defines += "REINHARD_TONEMAPPING";
  70005. else if (_this._operator === TonemappingOperator.HejiDawson)
  70006. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70007. else if (_this._operator === TonemappingOperator.Photographic)
  70008. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70009. //sadly a second call to create the effect.
  70010. _this.updateEffect(defines);
  70011. _this.onApply = function (effect) {
  70012. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70013. };
  70014. return _this;
  70015. }
  70016. return TonemapPostProcess;
  70017. }(BABYLON.PostProcess));
  70018. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70019. })(BABYLON || (BABYLON = {}));
  70020. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70021. var BABYLON;
  70022. (function (BABYLON) {
  70023. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70024. __extends(DisplayPassPostProcess, _super);
  70025. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70026. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70027. }
  70028. return DisplayPassPostProcess;
  70029. }(BABYLON.PostProcess));
  70030. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70031. })(BABYLON || (BABYLON = {}));
  70032. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70033. var BABYLON;
  70034. (function (BABYLON) {
  70035. var HighlightsPostProcess = /** @class */ (function (_super) {
  70036. __extends(HighlightsPostProcess, _super);
  70037. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70038. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70039. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70040. }
  70041. return HighlightsPostProcess;
  70042. }(BABYLON.PostProcess));
  70043. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70044. })(BABYLON || (BABYLON = {}));
  70045. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70046. var BABYLON;
  70047. (function (BABYLON) {
  70048. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70049. __extends(ImageProcessingPostProcess, _super);
  70050. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70051. if (camera === void 0) { camera = null; }
  70052. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70053. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70054. _this._fromLinearSpace = true;
  70055. /**
  70056. * Defines cache preventing GC.
  70057. */
  70058. _this._defines = {
  70059. IMAGEPROCESSING: false,
  70060. VIGNETTE: false,
  70061. VIGNETTEBLENDMODEMULTIPLY: false,
  70062. VIGNETTEBLENDMODEOPAQUE: false,
  70063. TONEMAPPING: false,
  70064. CONTRAST: false,
  70065. COLORCURVES: false,
  70066. COLORGRADING: false,
  70067. COLORGRADING3D: false,
  70068. FROMLINEARSPACE: false,
  70069. SAMPLER3DGREENDEPTH: false,
  70070. SAMPLER3DBGRMAP: false,
  70071. IMAGEPROCESSINGPOSTPROCESS: false,
  70072. EXPOSURE: false,
  70073. GRAIN: false,
  70074. };
  70075. // Setup the configuration as forced by the constructor. This would then not force the
  70076. // scene materials output in linear space and let untouched the default forward pass.
  70077. if (imageProcessingConfiguration) {
  70078. imageProcessingConfiguration.applyByPostProcess = true;
  70079. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70080. // This will cause the shader to be compiled
  70081. _this.fromLinearSpace = false;
  70082. }
  70083. else {
  70084. _this._attachImageProcessingConfiguration(null, true);
  70085. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70086. }
  70087. _this.onApply = function (effect) {
  70088. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70089. };
  70090. return _this;
  70091. }
  70092. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70093. /**
  70094. * Gets the image processing configuration used either in this material.
  70095. */
  70096. get: function () {
  70097. return this._imageProcessingConfiguration;
  70098. },
  70099. /**
  70100. * Sets the Default image processing configuration used either in the this material.
  70101. *
  70102. * If sets to null, the scene one is in use.
  70103. */
  70104. set: function (value) {
  70105. this._attachImageProcessingConfiguration(value);
  70106. },
  70107. enumerable: true,
  70108. configurable: true
  70109. });
  70110. /**
  70111. * Attaches a new image processing configuration to the PBR Material.
  70112. * @param configuration
  70113. */
  70114. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70115. var _this = this;
  70116. if (doNotBuild === void 0) { doNotBuild = false; }
  70117. if (configuration === this._imageProcessingConfiguration) {
  70118. return;
  70119. }
  70120. // Detaches observer.
  70121. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70122. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70123. }
  70124. // Pick the scene configuration if needed.
  70125. if (!configuration) {
  70126. var scene = null;
  70127. var engine = this.getEngine();
  70128. var camera = this.getCamera();
  70129. if (camera) {
  70130. scene = camera.getScene();
  70131. }
  70132. else if (engine && engine.scenes) {
  70133. var scenes = engine.scenes;
  70134. scene = scenes[scenes.length - 1];
  70135. }
  70136. else {
  70137. scene = BABYLON.Engine.LastCreatedScene;
  70138. }
  70139. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70140. }
  70141. else {
  70142. this._imageProcessingConfiguration = configuration;
  70143. }
  70144. // Attaches observer.
  70145. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70146. _this._updateParameters();
  70147. });
  70148. // Ensure the effect will be rebuilt.
  70149. if (!doNotBuild) {
  70150. this._updateParameters();
  70151. }
  70152. };
  70153. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70154. /**
  70155. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70156. */
  70157. get: function () {
  70158. return this.imageProcessingConfiguration.colorCurves;
  70159. },
  70160. /**
  70161. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70162. */
  70163. set: function (value) {
  70164. this.imageProcessingConfiguration.colorCurves = value;
  70165. },
  70166. enumerable: true,
  70167. configurable: true
  70168. });
  70169. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70170. /**
  70171. * Gets wether the color curves effect is enabled.
  70172. */
  70173. get: function () {
  70174. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70175. },
  70176. /**
  70177. * Sets wether the color curves effect is enabled.
  70178. */
  70179. set: function (value) {
  70180. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70181. },
  70182. enumerable: true,
  70183. configurable: true
  70184. });
  70185. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70186. /**
  70187. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70188. */
  70189. get: function () {
  70190. return this.imageProcessingConfiguration.colorGradingTexture;
  70191. },
  70192. /**
  70193. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70194. */
  70195. set: function (value) {
  70196. this.imageProcessingConfiguration.colorGradingTexture = value;
  70197. },
  70198. enumerable: true,
  70199. configurable: true
  70200. });
  70201. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70202. /**
  70203. * Gets wether the color grading effect is enabled.
  70204. */
  70205. get: function () {
  70206. return this.imageProcessingConfiguration.colorGradingEnabled;
  70207. },
  70208. /**
  70209. * Gets wether the color grading effect is enabled.
  70210. */
  70211. set: function (value) {
  70212. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70213. },
  70214. enumerable: true,
  70215. configurable: true
  70216. });
  70217. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70218. /**
  70219. * Gets exposure used in the effect.
  70220. */
  70221. get: function () {
  70222. return this.imageProcessingConfiguration.exposure;
  70223. },
  70224. /**
  70225. * Sets exposure used in the effect.
  70226. */
  70227. set: function (value) {
  70228. this.imageProcessingConfiguration.exposure = value;
  70229. },
  70230. enumerable: true,
  70231. configurable: true
  70232. });
  70233. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70234. /**
  70235. * Gets wether tonemapping is enabled or not.
  70236. */
  70237. get: function () {
  70238. return this._imageProcessingConfiguration.toneMappingEnabled;
  70239. },
  70240. /**
  70241. * Sets wether tonemapping is enabled or not
  70242. */
  70243. set: function (value) {
  70244. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. ;
  70250. ;
  70251. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70252. /**
  70253. * Gets contrast used in the effect.
  70254. */
  70255. get: function () {
  70256. return this.imageProcessingConfiguration.contrast;
  70257. },
  70258. /**
  70259. * Sets contrast used in the effect.
  70260. */
  70261. set: function (value) {
  70262. this.imageProcessingConfiguration.contrast = value;
  70263. },
  70264. enumerable: true,
  70265. configurable: true
  70266. });
  70267. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70268. /**
  70269. * Gets Vignette stretch size.
  70270. */
  70271. get: function () {
  70272. return this.imageProcessingConfiguration.vignetteStretch;
  70273. },
  70274. /**
  70275. * Sets Vignette stretch size.
  70276. */
  70277. set: function (value) {
  70278. this.imageProcessingConfiguration.vignetteStretch = value;
  70279. },
  70280. enumerable: true,
  70281. configurable: true
  70282. });
  70283. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70284. /**
  70285. * Gets Vignette centre X Offset.
  70286. */
  70287. get: function () {
  70288. return this.imageProcessingConfiguration.vignetteCentreX;
  70289. },
  70290. /**
  70291. * Sets Vignette centre X Offset.
  70292. */
  70293. set: function (value) {
  70294. this.imageProcessingConfiguration.vignetteCentreX = value;
  70295. },
  70296. enumerable: true,
  70297. configurable: true
  70298. });
  70299. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70300. /**
  70301. * Gets Vignette centre Y Offset.
  70302. */
  70303. get: function () {
  70304. return this.imageProcessingConfiguration.vignetteCentreY;
  70305. },
  70306. /**
  70307. * Sets Vignette centre Y Offset.
  70308. */
  70309. set: function (value) {
  70310. this.imageProcessingConfiguration.vignetteCentreY = value;
  70311. },
  70312. enumerable: true,
  70313. configurable: true
  70314. });
  70315. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70316. /**
  70317. * Gets Vignette weight or intensity of the vignette effect.
  70318. */
  70319. get: function () {
  70320. return this.imageProcessingConfiguration.vignetteWeight;
  70321. },
  70322. /**
  70323. * Sets Vignette weight or intensity of the vignette effect.
  70324. */
  70325. set: function (value) {
  70326. this.imageProcessingConfiguration.vignetteWeight = value;
  70327. },
  70328. enumerable: true,
  70329. configurable: true
  70330. });
  70331. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70332. /**
  70333. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70334. * if vignetteEnabled is set to true.
  70335. */
  70336. get: function () {
  70337. return this.imageProcessingConfiguration.vignetteColor;
  70338. },
  70339. /**
  70340. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70341. * if vignetteEnabled is set to true.
  70342. */
  70343. set: function (value) {
  70344. this.imageProcessingConfiguration.vignetteColor = value;
  70345. },
  70346. enumerable: true,
  70347. configurable: true
  70348. });
  70349. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70350. /**
  70351. * Gets Camera field of view used by the Vignette effect.
  70352. */
  70353. get: function () {
  70354. return this.imageProcessingConfiguration.vignetteCameraFov;
  70355. },
  70356. /**
  70357. * Sets Camera field of view used by the Vignette effect.
  70358. */
  70359. set: function (value) {
  70360. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70361. },
  70362. enumerable: true,
  70363. configurable: true
  70364. });
  70365. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70366. /**
  70367. * Gets the vignette blend mode allowing different kind of effect.
  70368. */
  70369. get: function () {
  70370. return this.imageProcessingConfiguration.vignetteBlendMode;
  70371. },
  70372. /**
  70373. * Sets the vignette blend mode allowing different kind of effect.
  70374. */
  70375. set: function (value) {
  70376. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70377. },
  70378. enumerable: true,
  70379. configurable: true
  70380. });
  70381. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70382. /**
  70383. * Gets wether the vignette effect is enabled.
  70384. */
  70385. get: function () {
  70386. return this.imageProcessingConfiguration.vignetteEnabled;
  70387. },
  70388. /**
  70389. * Sets wether the vignette effect is enabled.
  70390. */
  70391. set: function (value) {
  70392. this.imageProcessingConfiguration.vignetteEnabled = value;
  70393. },
  70394. enumerable: true,
  70395. configurable: true
  70396. });
  70397. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  70398. /**
  70399. * Gets wether the grain effect is enabled.
  70400. */
  70401. get: function () {
  70402. return this.imageProcessingConfiguration.grainEnabled;
  70403. },
  70404. /**
  70405. * Sets wether the grain effect is enabled.
  70406. */
  70407. set: function (value) {
  70408. this.imageProcessingConfiguration.grainEnabled = value;
  70409. },
  70410. enumerable: true,
  70411. configurable: true
  70412. });
  70413. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  70414. /**
  70415. * Gets the grain effect's intensity.
  70416. */
  70417. get: function () {
  70418. return this.imageProcessingConfiguration.grainIntensity;
  70419. },
  70420. /**
  70421. * Sets the grain effect's intensity.
  70422. */
  70423. set: function (value) {
  70424. this.imageProcessingConfiguration.grainIntensity = value;
  70425. },
  70426. enumerable: true,
  70427. configurable: true
  70428. });
  70429. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  70430. /**
  70431. * Gets wether the grain effect is animated.
  70432. */
  70433. get: function () {
  70434. return this.imageProcessingConfiguration.grainAnimated;
  70435. },
  70436. /**
  70437. * Sets wether the grain effect is animated.
  70438. */
  70439. set: function (value) {
  70440. this.imageProcessingConfiguration.grainAnimated = value;
  70441. },
  70442. enumerable: true,
  70443. configurable: true
  70444. });
  70445. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70446. /**
  70447. * Gets wether the input of the processing is in Gamma or Linear Space.
  70448. */
  70449. get: function () {
  70450. return this._fromLinearSpace;
  70451. },
  70452. /**
  70453. * Sets wether the input of the processing is in Gamma or Linear Space.
  70454. */
  70455. set: function (value) {
  70456. if (this._fromLinearSpace === value) {
  70457. return;
  70458. }
  70459. this._fromLinearSpace = value;
  70460. this._updateParameters();
  70461. },
  70462. enumerable: true,
  70463. configurable: true
  70464. });
  70465. ImageProcessingPostProcess.prototype.getClassName = function () {
  70466. return "ImageProcessingPostProcess";
  70467. };
  70468. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70469. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70470. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70471. var defines = "";
  70472. for (var define in this._defines) {
  70473. if (this._defines[define]) {
  70474. defines += "#define " + define + ";\r\n";
  70475. }
  70476. }
  70477. var samplers = ["textureSampler"];
  70478. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70479. var uniforms = ["scale"];
  70480. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70481. this.updateEffect(defines, uniforms, samplers);
  70482. };
  70483. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70484. _super.prototype.dispose.call(this, camera);
  70485. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70486. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70487. }
  70488. this.imageProcessingConfiguration.applyByPostProcess = false;
  70489. };
  70490. __decorate([
  70491. BABYLON.serialize()
  70492. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70493. return ImageProcessingPostProcess;
  70494. }(BABYLON.PostProcess));
  70495. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70496. })(BABYLON || (BABYLON = {}));
  70497. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70498. var BABYLON;
  70499. (function (BABYLON) {
  70500. var Bone = /** @class */ (function (_super) {
  70501. __extends(Bone, _super);
  70502. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70503. if (parentBone === void 0) { parentBone = null; }
  70504. if (localMatrix === void 0) { localMatrix = null; }
  70505. if (restPose === void 0) { restPose = null; }
  70506. if (baseMatrix === void 0) { baseMatrix = null; }
  70507. if (index === void 0) { index = null; }
  70508. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70509. _this.name = name;
  70510. _this.children = new Array();
  70511. _this.animations = new Array();
  70512. // Set this value to map this bone to a different index in the transform matrices.
  70513. // Set this value to -1 to exclude the bone from the transform matrices.
  70514. _this._index = null;
  70515. _this._worldTransform = new BABYLON.Matrix();
  70516. _this._absoluteTransform = new BABYLON.Matrix();
  70517. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70518. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70519. _this._scaleVector = BABYLON.Vector3.One();
  70520. _this._negateScaleChildren = BABYLON.Vector3.One();
  70521. _this._scalingDeterminant = 1;
  70522. _this._skeleton = skeleton;
  70523. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70524. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70525. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70526. _this._index = index;
  70527. skeleton.bones.push(_this);
  70528. _this.setParent(parentBone, false);
  70529. _this._updateDifferenceMatrix();
  70530. return _this;
  70531. }
  70532. Object.defineProperty(Bone.prototype, "_matrix", {
  70533. get: function () {
  70534. return this._localMatrix;
  70535. },
  70536. set: function (val) {
  70537. if (this._localMatrix) {
  70538. this._localMatrix.copyFrom(val);
  70539. }
  70540. else {
  70541. this._localMatrix = val;
  70542. }
  70543. },
  70544. enumerable: true,
  70545. configurable: true
  70546. });
  70547. // Members
  70548. Bone.prototype.getSkeleton = function () {
  70549. return this._skeleton;
  70550. };
  70551. Bone.prototype.getParent = function () {
  70552. return this._parent;
  70553. };
  70554. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70555. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70556. if (this._parent === parent) {
  70557. return;
  70558. }
  70559. if (this._parent) {
  70560. var index = this._parent.children.indexOf(this);
  70561. if (index !== -1) {
  70562. this._parent.children.splice(index, 1);
  70563. }
  70564. }
  70565. this._parent = parent;
  70566. if (this._parent) {
  70567. this._parent.children.push(this);
  70568. }
  70569. if (updateDifferenceMatrix) {
  70570. this._updateDifferenceMatrix();
  70571. }
  70572. };
  70573. Bone.prototype.getLocalMatrix = function () {
  70574. return this._localMatrix;
  70575. };
  70576. Bone.prototype.getBaseMatrix = function () {
  70577. return this._baseMatrix;
  70578. };
  70579. Bone.prototype.getRestPose = function () {
  70580. return this._restPose;
  70581. };
  70582. Bone.prototype.returnToRest = function () {
  70583. this.updateMatrix(this._restPose.clone());
  70584. };
  70585. Bone.prototype.getWorldMatrix = function () {
  70586. return this._worldTransform;
  70587. };
  70588. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70589. return this._invertedAbsoluteTransform;
  70590. };
  70591. Bone.prototype.getAbsoluteTransform = function () {
  70592. return this._absoluteTransform;
  70593. };
  70594. Object.defineProperty(Bone.prototype, "position", {
  70595. // Properties (matches AbstractMesh properties)
  70596. get: function () {
  70597. return this.getPosition();
  70598. },
  70599. set: function (newPosition) {
  70600. this.setPosition(newPosition);
  70601. },
  70602. enumerable: true,
  70603. configurable: true
  70604. });
  70605. Object.defineProperty(Bone.prototype, "rotation", {
  70606. get: function () {
  70607. return this.getRotation();
  70608. },
  70609. set: function (newRotation) {
  70610. this.setRotation(newRotation);
  70611. },
  70612. enumerable: true,
  70613. configurable: true
  70614. });
  70615. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70616. get: function () {
  70617. return this.getRotationQuaternion();
  70618. },
  70619. set: function (newRotation) {
  70620. this.setRotationQuaternion(newRotation);
  70621. },
  70622. enumerable: true,
  70623. configurable: true
  70624. });
  70625. Object.defineProperty(Bone.prototype, "scaling", {
  70626. get: function () {
  70627. return this.getScale();
  70628. },
  70629. set: function (newScaling) {
  70630. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70631. },
  70632. enumerable: true,
  70633. configurable: true
  70634. });
  70635. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70636. /**
  70637. * Gets the animation properties override
  70638. */
  70639. get: function () {
  70640. return this._skeleton.animationPropertiesOverride;
  70641. },
  70642. enumerable: true,
  70643. configurable: true
  70644. });
  70645. // Methods
  70646. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70647. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70648. this._baseMatrix = matrix.clone();
  70649. this._localMatrix = matrix.clone();
  70650. this._skeleton._markAsDirty();
  70651. if (updateDifferenceMatrix) {
  70652. this._updateDifferenceMatrix();
  70653. }
  70654. };
  70655. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70656. if (!rootMatrix) {
  70657. rootMatrix = this._baseMatrix;
  70658. }
  70659. if (this._parent) {
  70660. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70661. }
  70662. else {
  70663. this._absoluteTransform.copyFrom(rootMatrix);
  70664. }
  70665. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70666. for (var index = 0; index < this.children.length; index++) {
  70667. this.children[index]._updateDifferenceMatrix();
  70668. }
  70669. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70670. };
  70671. Bone.prototype.markAsDirty = function () {
  70672. this._currentRenderId++;
  70673. this._skeleton._markAsDirty();
  70674. };
  70675. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70676. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70677. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70678. // all animation may be coming from a library skeleton, so may need to create animation
  70679. if (this.animations.length === 0) {
  70680. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70681. this.animations[0].setKeys([]);
  70682. }
  70683. // get animation info / verify there is such a range from the source bone
  70684. var sourceRange = source.animations[0].getRange(rangeName);
  70685. if (!sourceRange) {
  70686. return false;
  70687. }
  70688. var from = sourceRange.from;
  70689. var to = sourceRange.to;
  70690. var sourceKeys = source.animations[0].getKeys();
  70691. // rescaling prep
  70692. var sourceBoneLength = source.length;
  70693. var sourceParent = source.getParent();
  70694. var parent = this.getParent();
  70695. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70696. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70697. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70698. var destKeys = this.animations[0].getKeys();
  70699. // loop vars declaration
  70700. var orig;
  70701. var origTranslation;
  70702. var mat;
  70703. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70704. orig = sourceKeys[key];
  70705. if (orig.frame >= from && orig.frame <= to) {
  70706. if (rescaleAsRequired) {
  70707. mat = orig.value.clone();
  70708. // scale based on parent ratio, when bone has parent
  70709. if (parentScalingReqd) {
  70710. origTranslation = mat.getTranslation();
  70711. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70712. // scale based on skeleton dimension ratio when root bone, and value is passed
  70713. }
  70714. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70715. origTranslation = mat.getTranslation();
  70716. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70717. // use original when root bone, and no data for skelDimensionsRatio
  70718. }
  70719. else {
  70720. mat = orig.value;
  70721. }
  70722. }
  70723. else {
  70724. mat = orig.value;
  70725. }
  70726. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70727. }
  70728. }
  70729. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70730. return true;
  70731. };
  70732. /**
  70733. * Translate the bone in local or world space.
  70734. * @param vec The amount to translate the bone.
  70735. * @param space The space that the translation is in.
  70736. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70737. */
  70738. Bone.prototype.translate = function (vec, space, mesh) {
  70739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70740. var lm = this.getLocalMatrix();
  70741. if (space == BABYLON.Space.LOCAL) {
  70742. lm.m[12] += vec.x;
  70743. lm.m[13] += vec.y;
  70744. lm.m[14] += vec.z;
  70745. }
  70746. else {
  70747. var wm = null;
  70748. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70749. if (mesh) {
  70750. wm = mesh.getWorldMatrix();
  70751. }
  70752. this._skeleton.computeAbsoluteTransforms();
  70753. var tmat = Bone._tmpMats[0];
  70754. var tvec = Bone._tmpVecs[0];
  70755. if (this._parent) {
  70756. if (mesh && wm) {
  70757. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70758. tmat.multiplyToRef(wm, tmat);
  70759. }
  70760. else {
  70761. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70762. }
  70763. }
  70764. tmat.m[12] = 0;
  70765. tmat.m[13] = 0;
  70766. tmat.m[14] = 0;
  70767. tmat.invert();
  70768. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70769. lm.m[12] += tvec.x;
  70770. lm.m[13] += tvec.y;
  70771. lm.m[14] += tvec.z;
  70772. }
  70773. this.markAsDirty();
  70774. };
  70775. /**
  70776. * Set the postion of the bone in local or world space.
  70777. * @param position The position to set the bone.
  70778. * @param space The space that the position is in.
  70779. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70780. */
  70781. Bone.prototype.setPosition = function (position, space, mesh) {
  70782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70783. var lm = this.getLocalMatrix();
  70784. if (space == BABYLON.Space.LOCAL) {
  70785. lm.m[12] = position.x;
  70786. lm.m[13] = position.y;
  70787. lm.m[14] = position.z;
  70788. }
  70789. else {
  70790. var wm = null;
  70791. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70792. if (mesh) {
  70793. wm = mesh.getWorldMatrix();
  70794. }
  70795. this._skeleton.computeAbsoluteTransforms();
  70796. var tmat = Bone._tmpMats[0];
  70797. var vec = Bone._tmpVecs[0];
  70798. if (this._parent) {
  70799. if (mesh && wm) {
  70800. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70801. tmat.multiplyToRef(wm, tmat);
  70802. }
  70803. else {
  70804. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70805. }
  70806. }
  70807. tmat.invert();
  70808. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70809. lm.m[12] = vec.x;
  70810. lm.m[13] = vec.y;
  70811. lm.m[14] = vec.z;
  70812. }
  70813. this.markAsDirty();
  70814. };
  70815. /**
  70816. * Set the absolute postion of the bone (world space).
  70817. * @param position The position to set the bone.
  70818. * @param mesh The mesh that this bone is attached to.
  70819. */
  70820. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70821. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70822. };
  70823. /**
  70824. * Set the scale of the bone on the x, y and z axes.
  70825. * @param x The scale of the bone on the x axis.
  70826. * @param x The scale of the bone on the y axis.
  70827. * @param z The scale of the bone on the z axis.
  70828. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70829. */
  70830. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70831. if (scaleChildren === void 0) { scaleChildren = false; }
  70832. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70833. if (!scaleChildren) {
  70834. this._negateScaleChildren.x = 1 / x;
  70835. this._negateScaleChildren.y = 1 / y;
  70836. this._negateScaleChildren.z = 1 / z;
  70837. }
  70838. this._syncScaleVector();
  70839. }
  70840. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70841. };
  70842. /**
  70843. * Scale the bone on the x, y and z axes.
  70844. * @param x The amount to scale the bone on the x axis.
  70845. * @param x The amount to scale the bone on the y axis.
  70846. * @param z The amount to scale the bone on the z axis.
  70847. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70848. */
  70849. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70850. if (scaleChildren === void 0) { scaleChildren = false; }
  70851. var locMat = this.getLocalMatrix();
  70852. var origLocMat = Bone._tmpMats[0];
  70853. origLocMat.copyFrom(locMat);
  70854. var origLocMatInv = Bone._tmpMats[1];
  70855. origLocMatInv.copyFrom(origLocMat);
  70856. origLocMatInv.invert();
  70857. var scaleMat = Bone._tmpMats[2];
  70858. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70859. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70860. this._scaleVector.x *= x;
  70861. this._scaleVector.y *= y;
  70862. this._scaleVector.z *= z;
  70863. locMat.multiplyToRef(origLocMatInv, locMat);
  70864. locMat.multiplyToRef(scaleMat, locMat);
  70865. locMat.multiplyToRef(origLocMat, locMat);
  70866. var parent = this.getParent();
  70867. if (parent) {
  70868. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70869. }
  70870. else {
  70871. this.getAbsoluteTransform().copyFrom(locMat);
  70872. }
  70873. var len = this.children.length;
  70874. scaleMat.invert();
  70875. for (var i = 0; i < len; i++) {
  70876. var child = this.children[i];
  70877. var cm = child.getLocalMatrix();
  70878. cm.multiplyToRef(scaleMat, cm);
  70879. var lm = child.getLocalMatrix();
  70880. lm.m[12] *= x;
  70881. lm.m[13] *= y;
  70882. lm.m[14] *= z;
  70883. }
  70884. this.computeAbsoluteTransforms();
  70885. if (scaleChildren) {
  70886. for (var i = 0; i < len; i++) {
  70887. this.children[i].scale(x, y, z, scaleChildren);
  70888. }
  70889. }
  70890. this.markAsDirty();
  70891. };
  70892. /**
  70893. * Set the yaw, pitch, and roll of the bone in local or world space.
  70894. * @param yaw The rotation of the bone on the y axis.
  70895. * @param pitch The rotation of the bone on the x axis.
  70896. * @param roll The rotation of the bone on the z axis.
  70897. * @param space The space that the axes of rotation are in.
  70898. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70899. */
  70900. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70901. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70902. var rotMat = Bone._tmpMats[0];
  70903. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70904. var rotMatInv = Bone._tmpMats[1];
  70905. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70906. rotMatInv.multiplyToRef(rotMat, rotMat);
  70907. this._rotateWithMatrix(rotMat, space, mesh);
  70908. };
  70909. /**
  70910. * Rotate the bone on an axis in local or world space.
  70911. * @param axis The axis to rotate the bone on.
  70912. * @param amount The amount to rotate the bone.
  70913. * @param space The space that the axis is in.
  70914. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70915. */
  70916. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70918. var rmat = Bone._tmpMats[0];
  70919. rmat.m[12] = 0;
  70920. rmat.m[13] = 0;
  70921. rmat.m[14] = 0;
  70922. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70923. this._rotateWithMatrix(rmat, space, mesh);
  70924. };
  70925. /**
  70926. * Set the rotation of the bone to a particular axis angle in local or world space.
  70927. * @param axis The axis to rotate the bone on.
  70928. * @param angle The angle that the bone should be rotated to.
  70929. * @param space The space that the axis is in.
  70930. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70931. */
  70932. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70934. var rotMat = Bone._tmpMats[0];
  70935. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70936. var rotMatInv = Bone._tmpMats[1];
  70937. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70938. rotMatInv.multiplyToRef(rotMat, rotMat);
  70939. this._rotateWithMatrix(rotMat, space, mesh);
  70940. };
  70941. /**
  70942. * Set the euler rotation of the bone in local of world space.
  70943. * @param rotation The euler rotation that the bone should be set to.
  70944. * @param space The space that the rotation is in.
  70945. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70946. */
  70947. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70949. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70950. };
  70951. /**
  70952. * Set the quaternion rotation of the bone in local of world space.
  70953. * @param quat The quaternion rotation that the bone should be set to.
  70954. * @param space The space that the rotation is in.
  70955. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70956. */
  70957. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70958. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70959. var rotMatInv = Bone._tmpMats[0];
  70960. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70961. var rotMat = Bone._tmpMats[1];
  70962. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70963. rotMatInv.multiplyToRef(rotMat, rotMat);
  70964. this._rotateWithMatrix(rotMat, space, mesh);
  70965. };
  70966. /**
  70967. * Set the rotation matrix of the bone in local of world space.
  70968. * @param rotMat The rotation matrix that the bone should be set to.
  70969. * @param space The space that the rotation is in.
  70970. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70971. */
  70972. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70974. var rotMatInv = Bone._tmpMats[0];
  70975. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70976. var rotMat2 = Bone._tmpMats[1];
  70977. rotMat2.copyFrom(rotMat);
  70978. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70979. this._rotateWithMatrix(rotMat2, space, mesh);
  70980. };
  70981. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70982. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70983. var lmat = this.getLocalMatrix();
  70984. var lx = lmat.m[12];
  70985. var ly = lmat.m[13];
  70986. var lz = lmat.m[14];
  70987. var parent = this.getParent();
  70988. var parentScale = Bone._tmpMats[3];
  70989. var parentScaleInv = Bone._tmpMats[4];
  70990. if (parent) {
  70991. if (space == BABYLON.Space.WORLD) {
  70992. if (mesh) {
  70993. parentScale.copyFrom(mesh.getWorldMatrix());
  70994. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70995. }
  70996. else {
  70997. parentScale.copyFrom(parent.getAbsoluteTransform());
  70998. }
  70999. }
  71000. else {
  71001. parentScale = parent._scaleMatrix;
  71002. }
  71003. parentScaleInv.copyFrom(parentScale);
  71004. parentScaleInv.invert();
  71005. lmat.multiplyToRef(parentScale, lmat);
  71006. lmat.multiplyToRef(rmat, lmat);
  71007. lmat.multiplyToRef(parentScaleInv, lmat);
  71008. }
  71009. else {
  71010. if (space == BABYLON.Space.WORLD && mesh) {
  71011. parentScale.copyFrom(mesh.getWorldMatrix());
  71012. parentScaleInv.copyFrom(parentScale);
  71013. parentScaleInv.invert();
  71014. lmat.multiplyToRef(parentScale, lmat);
  71015. lmat.multiplyToRef(rmat, lmat);
  71016. lmat.multiplyToRef(parentScaleInv, lmat);
  71017. }
  71018. else {
  71019. lmat.multiplyToRef(rmat, lmat);
  71020. }
  71021. }
  71022. lmat.m[12] = lx;
  71023. lmat.m[13] = ly;
  71024. lmat.m[14] = lz;
  71025. this.computeAbsoluteTransforms();
  71026. this.markAsDirty();
  71027. };
  71028. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71029. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71030. if (space == BABYLON.Space.WORLD) {
  71031. var scaleMatrix = Bone._tmpMats[2];
  71032. scaleMatrix.copyFrom(this._scaleMatrix);
  71033. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71034. if (mesh) {
  71035. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71036. var meshScale = Bone._tmpMats[3];
  71037. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71038. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71039. }
  71040. rotMatInv.invert();
  71041. scaleMatrix.m[0] *= this._scalingDeterminant;
  71042. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71043. }
  71044. else {
  71045. rotMatInv.copyFrom(this.getLocalMatrix());
  71046. rotMatInv.invert();
  71047. var scaleMatrix = Bone._tmpMats[2];
  71048. scaleMatrix.copyFrom(this._scaleMatrix);
  71049. if (this._parent) {
  71050. var pscaleMatrix = Bone._tmpMats[3];
  71051. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71052. pscaleMatrix.invert();
  71053. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71054. }
  71055. else {
  71056. scaleMatrix.m[0] *= this._scalingDeterminant;
  71057. }
  71058. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71059. }
  71060. };
  71061. /**
  71062. * Get the scale of the bone
  71063. * @returns the scale of the bone
  71064. */
  71065. Bone.prototype.getScale = function () {
  71066. return this._scaleVector.clone();
  71067. };
  71068. /**
  71069. * Copy the scale of the bone to a vector3.
  71070. * @param result The vector3 to copy the scale to
  71071. */
  71072. Bone.prototype.getScaleToRef = function (result) {
  71073. result.copyFrom(this._scaleVector);
  71074. };
  71075. /**
  71076. * Get the position of the bone in local or world space.
  71077. * @param space The space that the returned position is in.
  71078. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71079. * @returns The position of the bone
  71080. */
  71081. Bone.prototype.getPosition = function (space, mesh) {
  71082. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71083. if (mesh === void 0) { mesh = null; }
  71084. var pos = BABYLON.Vector3.Zero();
  71085. this.getPositionToRef(space, mesh, pos);
  71086. return pos;
  71087. };
  71088. /**
  71089. * Copy the position of the bone to a vector3 in local or world space.
  71090. * @param space The space that the returned position is in.
  71091. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71092. * @param result The vector3 to copy the position to.
  71093. */
  71094. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71095. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71096. if (space == BABYLON.Space.LOCAL) {
  71097. var lm = this.getLocalMatrix();
  71098. result.x = lm.m[12];
  71099. result.y = lm.m[13];
  71100. result.z = lm.m[14];
  71101. }
  71102. else {
  71103. var wm = null;
  71104. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71105. if (mesh) {
  71106. wm = mesh.getWorldMatrix();
  71107. }
  71108. this._skeleton.computeAbsoluteTransforms();
  71109. var tmat = Bone._tmpMats[0];
  71110. if (mesh && wm) {
  71111. tmat.copyFrom(this.getAbsoluteTransform());
  71112. tmat.multiplyToRef(wm, tmat);
  71113. }
  71114. else {
  71115. tmat = this.getAbsoluteTransform();
  71116. }
  71117. result.x = tmat.m[12];
  71118. result.y = tmat.m[13];
  71119. result.z = tmat.m[14];
  71120. }
  71121. };
  71122. /**
  71123. * Get the absolute position of the bone (world space).
  71124. * @param mesh The mesh that this bone is attached to.
  71125. * @returns The absolute position of the bone
  71126. */
  71127. Bone.prototype.getAbsolutePosition = function (mesh) {
  71128. if (mesh === void 0) { mesh = null; }
  71129. var pos = BABYLON.Vector3.Zero();
  71130. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71131. return pos;
  71132. };
  71133. /**
  71134. * Copy the absolute position of the bone (world space) to the result param.
  71135. * @param mesh The mesh that this bone is attached to.
  71136. * @param result The vector3 to copy the absolute position to.
  71137. */
  71138. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71139. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71140. };
  71141. /**
  71142. * Compute the absolute transforms of this bone and its children.
  71143. */
  71144. Bone.prototype.computeAbsoluteTransforms = function () {
  71145. if (this._parent) {
  71146. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71147. }
  71148. else {
  71149. this._absoluteTransform.copyFrom(this._localMatrix);
  71150. var poseMatrix = this._skeleton.getPoseMatrix();
  71151. if (poseMatrix) {
  71152. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71153. }
  71154. }
  71155. var children = this.children;
  71156. var len = children.length;
  71157. for (var i = 0; i < len; i++) {
  71158. children[i].computeAbsoluteTransforms();
  71159. }
  71160. };
  71161. Bone.prototype._syncScaleVector = function () {
  71162. var lm = this.getLocalMatrix();
  71163. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71164. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71165. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71166. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71167. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71168. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71169. this._scaleVector.x = xs * Math.sqrt(xsq);
  71170. this._scaleVector.y = ys * Math.sqrt(ysq);
  71171. this._scaleVector.z = zs * Math.sqrt(zsq);
  71172. if (this._parent) {
  71173. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71174. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71175. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71176. }
  71177. 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);
  71178. };
  71179. /**
  71180. * Get the world direction from an axis that is in the local space of the bone.
  71181. * @param localAxis The local direction that is used to compute the world direction.
  71182. * @param mesh The mesh that this bone is attached to.
  71183. * @returns The world direction
  71184. */
  71185. Bone.prototype.getDirection = function (localAxis, mesh) {
  71186. if (mesh === void 0) { mesh = null; }
  71187. var result = BABYLON.Vector3.Zero();
  71188. this.getDirectionToRef(localAxis, mesh, result);
  71189. return result;
  71190. };
  71191. /**
  71192. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71193. * @param localAxis The local direction that is used to compute the world direction.
  71194. * @param mesh The mesh that this bone is attached to.
  71195. * @param result The vector3 that the world direction will be copied to.
  71196. */
  71197. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71198. if (mesh === void 0) { mesh = null; }
  71199. var wm = null;
  71200. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71201. if (mesh) {
  71202. wm = mesh.getWorldMatrix();
  71203. }
  71204. this._skeleton.computeAbsoluteTransforms();
  71205. var mat = Bone._tmpMats[0];
  71206. mat.copyFrom(this.getAbsoluteTransform());
  71207. if (mesh && wm) {
  71208. mat.multiplyToRef(wm, mat);
  71209. }
  71210. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71211. result.normalize();
  71212. };
  71213. /**
  71214. * Get the euler rotation of the bone in local or world space.
  71215. * @param space The space that the rotation should be in.
  71216. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71217. * @returns The euler rotation
  71218. */
  71219. Bone.prototype.getRotation = function (space, mesh) {
  71220. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71221. if (mesh === void 0) { mesh = null; }
  71222. var result = BABYLON.Vector3.Zero();
  71223. this.getRotationToRef(space, mesh, result);
  71224. return result;
  71225. };
  71226. /**
  71227. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71228. * @param space The space that the rotation should be in.
  71229. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71230. * @param result The vector3 that the rotation should be copied to.
  71231. */
  71232. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71234. if (mesh === void 0) { mesh = null; }
  71235. var quat = Bone._tmpQuat;
  71236. this.getRotationQuaternionToRef(space, mesh, quat);
  71237. quat.toEulerAnglesToRef(result);
  71238. };
  71239. /**
  71240. * Get the quaternion rotation of the bone in either local or world space.
  71241. * @param space The space that the rotation should be in.
  71242. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71243. * @returns The quaternion rotation
  71244. */
  71245. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71247. if (mesh === void 0) { mesh = null; }
  71248. var result = BABYLON.Quaternion.Identity();
  71249. this.getRotationQuaternionToRef(space, mesh, result);
  71250. return result;
  71251. };
  71252. /**
  71253. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71254. * @param space The space that the rotation should be in.
  71255. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71256. * @param result The quaternion that the rotation should be copied to.
  71257. */
  71258. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71259. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71260. if (mesh === void 0) { mesh = null; }
  71261. if (space == BABYLON.Space.LOCAL) {
  71262. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71263. }
  71264. else {
  71265. var mat = Bone._tmpMats[0];
  71266. var amat = this.getAbsoluteTransform();
  71267. if (mesh) {
  71268. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71269. }
  71270. else {
  71271. mat.copyFrom(amat);
  71272. }
  71273. mat.m[0] *= this._scalingDeterminant;
  71274. mat.m[1] *= this._scalingDeterminant;
  71275. mat.m[2] *= this._scalingDeterminant;
  71276. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71277. }
  71278. };
  71279. /**
  71280. * Get the rotation matrix of the bone in local or world space.
  71281. * @param space The space that the rotation should be in.
  71282. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71283. * @returns The rotation matrix
  71284. */
  71285. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71287. var result = BABYLON.Matrix.Identity();
  71288. this.getRotationMatrixToRef(space, mesh, result);
  71289. return result;
  71290. };
  71291. /**
  71292. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71293. * @param space The space that the rotation should be in.
  71294. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71295. * @param result The quaternion that the rotation should be copied to.
  71296. */
  71297. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71299. if (space == BABYLON.Space.LOCAL) {
  71300. this.getLocalMatrix().getRotationMatrixToRef(result);
  71301. }
  71302. else {
  71303. var mat = Bone._tmpMats[0];
  71304. var amat = this.getAbsoluteTransform();
  71305. if (mesh) {
  71306. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71307. }
  71308. else {
  71309. mat.copyFrom(amat);
  71310. }
  71311. mat.m[0] *= this._scalingDeterminant;
  71312. mat.m[1] *= this._scalingDeterminant;
  71313. mat.m[2] *= this._scalingDeterminant;
  71314. mat.getRotationMatrixToRef(result);
  71315. }
  71316. };
  71317. /**
  71318. * Get the world position of a point that is in the local space of the bone.
  71319. * @param position The local position
  71320. * @param mesh The mesh that this bone is attached to.
  71321. * @returns The world position
  71322. */
  71323. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71324. if (mesh === void 0) { mesh = null; }
  71325. var result = BABYLON.Vector3.Zero();
  71326. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71327. return result;
  71328. };
  71329. /**
  71330. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71331. * @param position The local position
  71332. * @param mesh The mesh that this bone is attached to.
  71333. * @param result The vector3 that the world position should be copied to.
  71334. */
  71335. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71336. if (mesh === void 0) { mesh = null; }
  71337. var wm = null;
  71338. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71339. if (mesh) {
  71340. wm = mesh.getWorldMatrix();
  71341. }
  71342. this._skeleton.computeAbsoluteTransforms();
  71343. var tmat = Bone._tmpMats[0];
  71344. if (mesh && wm) {
  71345. tmat.copyFrom(this.getAbsoluteTransform());
  71346. tmat.multiplyToRef(wm, tmat);
  71347. }
  71348. else {
  71349. tmat = this.getAbsoluteTransform();
  71350. }
  71351. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71352. };
  71353. /**
  71354. * Get the local position of a point that is in world space.
  71355. * @param position The world position
  71356. * @param mesh The mesh that this bone is attached to.
  71357. * @returns The local position
  71358. */
  71359. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71360. if (mesh === void 0) { mesh = null; }
  71361. var result = BABYLON.Vector3.Zero();
  71362. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71363. return result;
  71364. };
  71365. /**
  71366. * Get the local position of a point that is in world space and copy it to the result param.
  71367. * @param position The world position
  71368. * @param mesh The mesh that this bone is attached to.
  71369. * @param result The vector3 that the local position should be copied to.
  71370. */
  71371. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71372. if (mesh === void 0) { mesh = null; }
  71373. var wm = null;
  71374. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71375. if (mesh) {
  71376. wm = mesh.getWorldMatrix();
  71377. }
  71378. this._skeleton.computeAbsoluteTransforms();
  71379. var tmat = Bone._tmpMats[0];
  71380. tmat.copyFrom(this.getAbsoluteTransform());
  71381. if (mesh && wm) {
  71382. tmat.multiplyToRef(wm, tmat);
  71383. }
  71384. tmat.invert();
  71385. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71386. };
  71387. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71388. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71389. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71390. return Bone;
  71391. }(BABYLON.Node));
  71392. BABYLON.Bone = Bone;
  71393. })(BABYLON || (BABYLON = {}));
  71394. //# sourceMappingURL=babylon.bone.js.map
  71395. var BABYLON;
  71396. (function (BABYLON) {
  71397. var BoneIKController = /** @class */ (function () {
  71398. function BoneIKController(mesh, bone, options) {
  71399. this.targetPosition = BABYLON.Vector3.Zero();
  71400. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71401. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71402. this.poleAngle = 0;
  71403. this.slerpAmount = 1;
  71404. this._bone1Quat = BABYLON.Quaternion.Identity();
  71405. this._bone1Mat = BABYLON.Matrix.Identity();
  71406. this._bone2Ang = Math.PI;
  71407. this._maxAngle = Math.PI;
  71408. this._rightHandedSystem = false;
  71409. this._bendAxis = BABYLON.Vector3.Right();
  71410. this._slerping = false;
  71411. this._adjustRoll = 0;
  71412. this._bone2 = bone;
  71413. this._bone1 = bone.getParent();
  71414. if (!this._bone1) {
  71415. return;
  71416. }
  71417. this.mesh = mesh;
  71418. var bonePos = bone.getPosition();
  71419. if (bone.getAbsoluteTransform().determinant() > 0) {
  71420. this._rightHandedSystem = true;
  71421. this._bendAxis.x = 0;
  71422. this._bendAxis.y = 0;
  71423. this._bendAxis.z = -1;
  71424. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71425. this._adjustRoll = Math.PI * .5;
  71426. this._bendAxis.z = 1;
  71427. }
  71428. }
  71429. if (this._bone1.length) {
  71430. var boneScale1 = this._bone1.getScale();
  71431. var boneScale2 = this._bone2.getScale();
  71432. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71433. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71434. }
  71435. else if (this._bone1.children[0]) {
  71436. mesh.computeWorldMatrix(true);
  71437. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71438. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71439. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71440. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71441. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71442. }
  71443. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71444. this.maxAngle = Math.PI;
  71445. if (options) {
  71446. if (options.targetMesh) {
  71447. this.targetMesh = options.targetMesh;
  71448. this.targetMesh.computeWorldMatrix(true);
  71449. }
  71450. if (options.poleTargetMesh) {
  71451. this.poleTargetMesh = options.poleTargetMesh;
  71452. this.poleTargetMesh.computeWorldMatrix(true);
  71453. }
  71454. else if (options.poleTargetBone) {
  71455. this.poleTargetBone = options.poleTargetBone;
  71456. }
  71457. else if (this._bone1.getParent()) {
  71458. this.poleTargetBone = this._bone1.getParent();
  71459. }
  71460. if (options.poleTargetLocalOffset) {
  71461. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71462. }
  71463. if (options.poleAngle) {
  71464. this.poleAngle = options.poleAngle;
  71465. }
  71466. if (options.bendAxis) {
  71467. this._bendAxis.copyFrom(options.bendAxis);
  71468. }
  71469. if (options.maxAngle) {
  71470. this.maxAngle = options.maxAngle;
  71471. }
  71472. if (options.slerpAmount) {
  71473. this.slerpAmount = options.slerpAmount;
  71474. }
  71475. }
  71476. }
  71477. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71478. get: function () {
  71479. return this._maxAngle;
  71480. },
  71481. set: function (value) {
  71482. this._setMaxAngle(value);
  71483. },
  71484. enumerable: true,
  71485. configurable: true
  71486. });
  71487. BoneIKController.prototype._setMaxAngle = function (ang) {
  71488. if (ang < 0) {
  71489. ang = 0;
  71490. }
  71491. if (ang > Math.PI || ang == undefined) {
  71492. ang = Math.PI;
  71493. }
  71494. this._maxAngle = ang;
  71495. var a = this._bone1Length;
  71496. var b = this._bone2Length;
  71497. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71498. };
  71499. BoneIKController.prototype.update = function () {
  71500. var bone1 = this._bone1;
  71501. if (!bone1) {
  71502. return;
  71503. }
  71504. var target = this.targetPosition;
  71505. var poleTarget = this.poleTargetPosition;
  71506. var mat1 = BoneIKController._tmpMats[0];
  71507. var mat2 = BoneIKController._tmpMats[1];
  71508. if (this.targetMesh) {
  71509. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71510. }
  71511. if (this.poleTargetBone) {
  71512. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71513. }
  71514. else if (this.poleTargetMesh) {
  71515. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71516. }
  71517. var bonePos = BoneIKController._tmpVecs[0];
  71518. var zaxis = BoneIKController._tmpVecs[1];
  71519. var xaxis = BoneIKController._tmpVecs[2];
  71520. var yaxis = BoneIKController._tmpVecs[3];
  71521. var upAxis = BoneIKController._tmpVecs[4];
  71522. var _tmpQuat = BoneIKController._tmpQuat;
  71523. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71524. poleTarget.subtractToRef(bonePos, upAxis);
  71525. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71526. upAxis.y = 1;
  71527. }
  71528. else {
  71529. upAxis.normalize();
  71530. }
  71531. target.subtractToRef(bonePos, yaxis);
  71532. yaxis.normalize();
  71533. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71534. zaxis.normalize();
  71535. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71536. xaxis.normalize();
  71537. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71538. var a = this._bone1Length;
  71539. var b = this._bone2Length;
  71540. var c = BABYLON.Vector3.Distance(bonePos, target);
  71541. if (this._maxReach > 0) {
  71542. c = Math.min(this._maxReach, c);
  71543. }
  71544. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71545. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71546. if (acosa > 1) {
  71547. acosa = 1;
  71548. }
  71549. if (acosb > 1) {
  71550. acosb = 1;
  71551. }
  71552. if (acosa < -1) {
  71553. acosa = -1;
  71554. }
  71555. if (acosb < -1) {
  71556. acosb = -1;
  71557. }
  71558. var angA = Math.acos(acosa);
  71559. var angB = Math.acos(acosb);
  71560. var angC = -angA - angB;
  71561. if (this._rightHandedSystem) {
  71562. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71563. mat2.multiplyToRef(mat1, mat1);
  71564. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71565. mat2.multiplyToRef(mat1, mat1);
  71566. }
  71567. else {
  71568. var _tmpVec = BoneIKController._tmpVecs[5];
  71569. _tmpVec.copyFrom(this._bendAxis);
  71570. _tmpVec.x *= -1;
  71571. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71572. mat2.multiplyToRef(mat1, mat1);
  71573. }
  71574. if (this.poleAngle) {
  71575. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71576. mat1.multiplyToRef(mat2, mat1);
  71577. }
  71578. if (this._bone1) {
  71579. if (this.slerpAmount < 1) {
  71580. if (!this._slerping) {
  71581. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71582. }
  71583. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71584. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71585. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71586. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71587. this._slerping = true;
  71588. }
  71589. else {
  71590. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71591. this._bone1Mat.copyFrom(mat1);
  71592. this._slerping = false;
  71593. }
  71594. }
  71595. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71596. this._bone2Ang = angC;
  71597. };
  71598. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71599. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71600. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71601. return BoneIKController;
  71602. }());
  71603. BABYLON.BoneIKController = BoneIKController;
  71604. })(BABYLON || (BABYLON = {}));
  71605. //# sourceMappingURL=babylon.boneIKController.js.map
  71606. var BABYLON;
  71607. (function (BABYLON) {
  71608. var BoneLookController = /** @class */ (function () {
  71609. /**
  71610. * Create a BoneLookController
  71611. * @param mesh the mesh that the bone belongs to
  71612. * @param bone the bone that will be looking to the target
  71613. * @param target the target Vector3 to look at
  71614. * @param settings optional settings:
  71615. * - maxYaw: the maximum angle the bone will yaw to
  71616. * - minYaw: the minimum angle the bone will yaw to
  71617. * - maxPitch: the maximum angle the bone will pitch to
  71618. * - minPitch: the minimum angle the bone will yaw to
  71619. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71620. * - upAxis: the up axis of the coordinate system
  71621. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71622. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71623. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71624. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71625. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71626. * - adjustRoll: used to make an adjustment to the roll of the bone
  71627. **/
  71628. function BoneLookController(mesh, bone, target, options) {
  71629. /**
  71630. * The up axis of the coordinate system that is used when the bone is rotated.
  71631. */
  71632. this.upAxis = BABYLON.Vector3.Up();
  71633. /**
  71634. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71635. */
  71636. this.upAxisSpace = BABYLON.Space.LOCAL;
  71637. /**
  71638. * Used to make an adjustment to the yaw of the bone.
  71639. */
  71640. this.adjustYaw = 0;
  71641. /**
  71642. * Used to make an adjustment to the pitch of the bone.
  71643. */
  71644. this.adjustPitch = 0;
  71645. /**
  71646. * Used to make an adjustment to the roll of the bone.
  71647. */
  71648. this.adjustRoll = 0;
  71649. /**
  71650. * 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).
  71651. */
  71652. this.slerpAmount = 1;
  71653. this._boneQuat = BABYLON.Quaternion.Identity();
  71654. this._slerping = false;
  71655. this._firstFrameSkipped = false;
  71656. this._fowardAxis = BABYLON.Vector3.Forward();
  71657. this.mesh = mesh;
  71658. this.bone = bone;
  71659. this.target = target;
  71660. if (options) {
  71661. if (options.adjustYaw) {
  71662. this.adjustYaw = options.adjustYaw;
  71663. }
  71664. if (options.adjustPitch) {
  71665. this.adjustPitch = options.adjustPitch;
  71666. }
  71667. if (options.adjustRoll) {
  71668. this.adjustRoll = options.adjustRoll;
  71669. }
  71670. if (options.maxYaw != null) {
  71671. this.maxYaw = options.maxYaw;
  71672. }
  71673. else {
  71674. this.maxYaw = Math.PI;
  71675. }
  71676. if (options.minYaw != null) {
  71677. this.minYaw = options.minYaw;
  71678. }
  71679. else {
  71680. this.minYaw = -Math.PI;
  71681. }
  71682. if (options.maxPitch != null) {
  71683. this.maxPitch = options.maxPitch;
  71684. }
  71685. else {
  71686. this.maxPitch = Math.PI;
  71687. }
  71688. if (options.minPitch != null) {
  71689. this.minPitch = options.minPitch;
  71690. }
  71691. else {
  71692. this.minPitch = -Math.PI;
  71693. }
  71694. if (options.slerpAmount != null) {
  71695. this.slerpAmount = options.slerpAmount;
  71696. }
  71697. if (options.upAxis != null) {
  71698. this.upAxis = options.upAxis;
  71699. }
  71700. if (options.upAxisSpace != null) {
  71701. this.upAxisSpace = options.upAxisSpace;
  71702. }
  71703. if (options.yawAxis != null || options.pitchAxis != null) {
  71704. var newYawAxis = BABYLON.Axis.Y;
  71705. var newPitchAxis = BABYLON.Axis.X;
  71706. if (options.yawAxis != null) {
  71707. newYawAxis = options.yawAxis.clone();
  71708. newYawAxis.normalize();
  71709. }
  71710. if (options.pitchAxis != null) {
  71711. newPitchAxis = options.pitchAxis.clone();
  71712. newPitchAxis.normalize();
  71713. }
  71714. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71715. this._transformYawPitch = BABYLON.Matrix.Identity();
  71716. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71717. this._transformYawPitchInv = this._transformYawPitch.clone();
  71718. this._transformYawPitch.invert();
  71719. }
  71720. }
  71721. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71722. this.upAxisSpace = BABYLON.Space.LOCAL;
  71723. }
  71724. }
  71725. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71726. /**
  71727. * Get/set the minimum yaw angle that the bone can look to.
  71728. */
  71729. get: function () {
  71730. return this._minYaw;
  71731. },
  71732. set: function (value) {
  71733. this._minYaw = value;
  71734. this._minYawSin = Math.sin(value);
  71735. this._minYawCos = Math.cos(value);
  71736. if (this._maxYaw != null) {
  71737. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71738. this._yawRange = this._maxYaw - this._minYaw;
  71739. }
  71740. },
  71741. enumerable: true,
  71742. configurable: true
  71743. });
  71744. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71745. /**
  71746. * Get/set the maximum yaw angle that the bone can look to.
  71747. */
  71748. get: function () {
  71749. return this._maxYaw;
  71750. },
  71751. set: function (value) {
  71752. this._maxYaw = value;
  71753. this._maxYawSin = Math.sin(value);
  71754. this._maxYawCos = Math.cos(value);
  71755. if (this._minYaw != null) {
  71756. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71757. this._yawRange = this._maxYaw - this._minYaw;
  71758. }
  71759. },
  71760. enumerable: true,
  71761. configurable: true
  71762. });
  71763. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71764. /**
  71765. * Get/set the minimum pitch angle that the bone can look to.
  71766. */
  71767. get: function () {
  71768. return this._minPitch;
  71769. },
  71770. set: function (value) {
  71771. this._minPitch = value;
  71772. this._minPitchTan = Math.tan(value);
  71773. },
  71774. enumerable: true,
  71775. configurable: true
  71776. });
  71777. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71778. /**
  71779. * Get/set the maximum pitch angle that the bone can look to.
  71780. */
  71781. get: function () {
  71782. return this._maxPitch;
  71783. },
  71784. set: function (value) {
  71785. this._maxPitch = value;
  71786. this._maxPitchTan = Math.tan(value);
  71787. },
  71788. enumerable: true,
  71789. configurable: true
  71790. });
  71791. /**
  71792. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71793. */
  71794. BoneLookController.prototype.update = function () {
  71795. //skip the first frame when slerping so that the mesh rotation is correct
  71796. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71797. this._firstFrameSkipped = true;
  71798. return;
  71799. }
  71800. var bone = this.bone;
  71801. var bonePos = BoneLookController._tmpVecs[0];
  71802. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71803. var target = this.target;
  71804. var _tmpMat1 = BoneLookController._tmpMats[0];
  71805. var _tmpMat2 = BoneLookController._tmpMats[1];
  71806. var mesh = this.mesh;
  71807. var parentBone = bone.getParent();
  71808. var upAxis = BoneLookController._tmpVecs[1];
  71809. upAxis.copyFrom(this.upAxis);
  71810. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71811. if (this._transformYawPitch) {
  71812. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71813. }
  71814. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71815. }
  71816. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71817. mesh.getDirectionToRef(upAxis, upAxis);
  71818. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71819. upAxis.normalize();
  71820. }
  71821. }
  71822. var checkYaw = false;
  71823. var checkPitch = false;
  71824. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71825. checkYaw = true;
  71826. }
  71827. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71828. checkPitch = true;
  71829. }
  71830. if (checkYaw || checkPitch) {
  71831. var spaceMat = BoneLookController._tmpMats[2];
  71832. var spaceMatInv = BoneLookController._tmpMats[3];
  71833. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71834. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71835. }
  71836. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71837. spaceMat.copyFrom(mesh.getWorldMatrix());
  71838. }
  71839. else {
  71840. var forwardAxis = BoneLookController._tmpVecs[2];
  71841. forwardAxis.copyFrom(this._fowardAxis);
  71842. if (this._transformYawPitch) {
  71843. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71844. }
  71845. if (parentBone) {
  71846. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71847. }
  71848. else {
  71849. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71850. }
  71851. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71852. rightAxis.normalize();
  71853. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71854. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71855. }
  71856. spaceMat.invertToRef(spaceMatInv);
  71857. var xzlen = null;
  71858. if (checkPitch) {
  71859. var localTarget = BoneLookController._tmpVecs[3];
  71860. target.subtractToRef(bonePos, localTarget);
  71861. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71862. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71863. var pitch = Math.atan2(localTarget.y, xzlen);
  71864. var newPitch = pitch;
  71865. if (pitch > this._maxPitch) {
  71866. localTarget.y = this._maxPitchTan * xzlen;
  71867. newPitch = this._maxPitch;
  71868. }
  71869. else if (pitch < this._minPitch) {
  71870. localTarget.y = this._minPitchTan * xzlen;
  71871. newPitch = this._minPitch;
  71872. }
  71873. if (pitch != newPitch) {
  71874. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71875. localTarget.addInPlace(bonePos);
  71876. target = localTarget;
  71877. }
  71878. }
  71879. if (checkYaw) {
  71880. var localTarget = BoneLookController._tmpVecs[4];
  71881. target.subtractToRef(bonePos, localTarget);
  71882. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71883. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71884. var newYaw = yaw;
  71885. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71886. if (xzlen == null) {
  71887. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71888. }
  71889. if (this._yawRange > Math.PI) {
  71890. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71891. localTarget.z = this._maxYawCos * xzlen;
  71892. localTarget.x = this._maxYawSin * xzlen;
  71893. newYaw = this._maxYaw;
  71894. }
  71895. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71896. localTarget.z = this._minYawCos * xzlen;
  71897. localTarget.x = this._minYawSin * xzlen;
  71898. newYaw = this._minYaw;
  71899. }
  71900. }
  71901. else {
  71902. if (yaw > this._maxYaw) {
  71903. localTarget.z = this._maxYawCos * xzlen;
  71904. localTarget.x = this._maxYawSin * xzlen;
  71905. newYaw = this._maxYaw;
  71906. }
  71907. else if (yaw < this._minYaw) {
  71908. localTarget.z = this._minYawCos * xzlen;
  71909. localTarget.x = this._minYawSin * xzlen;
  71910. newYaw = this._minYaw;
  71911. }
  71912. }
  71913. }
  71914. if (this._slerping && this._yawRange > Math.PI) {
  71915. //are we going to be crossing into the min/max region?
  71916. var boneFwd = BoneLookController._tmpVecs[8];
  71917. boneFwd.copyFrom(BABYLON.Axis.Z);
  71918. if (this._transformYawPitch) {
  71919. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71920. }
  71921. var boneRotMat = BoneLookController._tmpMats[4];
  71922. this._boneQuat.toRotationMatrix(boneRotMat);
  71923. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71924. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71925. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71926. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71927. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71928. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71929. if (angBtwTar > angBtwMidYaw) {
  71930. if (xzlen == null) {
  71931. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71932. }
  71933. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71934. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71935. if (angBtwMin < angBtwMax) {
  71936. newYaw = boneYaw + Math.PI * .75;
  71937. localTarget.z = Math.cos(newYaw) * xzlen;
  71938. localTarget.x = Math.sin(newYaw) * xzlen;
  71939. }
  71940. else {
  71941. newYaw = boneYaw - Math.PI * .75;
  71942. localTarget.z = Math.cos(newYaw) * xzlen;
  71943. localTarget.x = Math.sin(newYaw) * xzlen;
  71944. }
  71945. }
  71946. }
  71947. if (yaw != newYaw) {
  71948. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71949. localTarget.addInPlace(bonePos);
  71950. target = localTarget;
  71951. }
  71952. }
  71953. }
  71954. var zaxis = BoneLookController._tmpVecs[5];
  71955. var xaxis = BoneLookController._tmpVecs[6];
  71956. var yaxis = BoneLookController._tmpVecs[7];
  71957. var _tmpQuat = BoneLookController._tmpQuat;
  71958. target.subtractToRef(bonePos, zaxis);
  71959. zaxis.normalize();
  71960. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71961. xaxis.normalize();
  71962. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71963. yaxis.normalize();
  71964. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71965. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71966. return;
  71967. }
  71968. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71969. return;
  71970. }
  71971. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71972. return;
  71973. }
  71974. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71975. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71976. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71977. }
  71978. if (this.slerpAmount < 1) {
  71979. if (!this._slerping) {
  71980. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71981. }
  71982. if (this._transformYawPitch) {
  71983. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71984. }
  71985. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71986. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71987. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71988. this._slerping = true;
  71989. }
  71990. else {
  71991. if (this._transformYawPitch) {
  71992. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71993. }
  71994. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71995. this._slerping = false;
  71996. }
  71997. };
  71998. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71999. var angDiff = ang2 - ang1;
  72000. angDiff %= Math.PI * 2;
  72001. if (angDiff > Math.PI) {
  72002. angDiff -= Math.PI * 2;
  72003. }
  72004. else if (angDiff < -Math.PI) {
  72005. angDiff += Math.PI * 2;
  72006. }
  72007. return angDiff;
  72008. };
  72009. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72010. ang1 %= (2 * Math.PI);
  72011. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72012. ang2 %= (2 * Math.PI);
  72013. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72014. var ab = 0;
  72015. if (ang1 < ang2) {
  72016. ab = ang2 - ang1;
  72017. }
  72018. else {
  72019. ab = ang1 - ang2;
  72020. }
  72021. if (ab > Math.PI) {
  72022. ab = Math.PI * 2 - ab;
  72023. }
  72024. return ab;
  72025. };
  72026. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72027. ang %= (2 * Math.PI);
  72028. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72029. ang1 %= (2 * Math.PI);
  72030. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72031. ang2 %= (2 * Math.PI);
  72032. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72033. if (ang1 < ang2) {
  72034. if (ang > ang1 && ang < ang2) {
  72035. return true;
  72036. }
  72037. }
  72038. else {
  72039. if (ang > ang2 && ang < ang1) {
  72040. return true;
  72041. }
  72042. }
  72043. return false;
  72044. };
  72045. 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()];
  72046. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72047. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72048. return BoneLookController;
  72049. }());
  72050. BABYLON.BoneLookController = BoneLookController;
  72051. })(BABYLON || (BABYLON = {}));
  72052. //# sourceMappingURL=babylon.boneLookController.js.map
  72053. var BABYLON;
  72054. (function (BABYLON) {
  72055. var Skeleton = /** @class */ (function () {
  72056. function Skeleton(name, id, scene) {
  72057. this.name = name;
  72058. this.id = id;
  72059. this.bones = new Array();
  72060. this.needInitialSkinMatrix = false;
  72061. this._isDirty = true;
  72062. this._meshesWithPoseMatrix = new Array();
  72063. this._identity = BABYLON.Matrix.Identity();
  72064. this._ranges = {};
  72065. this._lastAbsoluteTransformsUpdateId = -1;
  72066. /**
  72067. * Specifies if the skeleton should be serialized.
  72068. */
  72069. this.doNotSerialize = false;
  72070. // Events
  72071. /**
  72072. * An event triggered before computing the skeleton's matrices
  72073. * @type {BABYLON.Observable}
  72074. */
  72075. this.onBeforeComputeObservable = new BABYLON.Observable();
  72076. this.bones = [];
  72077. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72078. scene.skeletons.push(this);
  72079. //make sure it will recalculate the matrix next time prepare is called.
  72080. this._isDirty = true;
  72081. }
  72082. // Members
  72083. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72084. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72085. return mesh._bonesTransformMatrices;
  72086. }
  72087. if (!this._transformMatrices) {
  72088. this.prepare();
  72089. }
  72090. return this._transformMatrices;
  72091. };
  72092. Skeleton.prototype.getScene = function () {
  72093. return this._scene;
  72094. };
  72095. // Methods
  72096. /**
  72097. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72098. */
  72099. Skeleton.prototype.toString = function (fullDetails) {
  72100. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72101. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72102. if (fullDetails) {
  72103. ret += ", Ranges: {";
  72104. var first = true;
  72105. for (var name_1 in this._ranges) {
  72106. if (first) {
  72107. ret += ", ";
  72108. first = false;
  72109. }
  72110. ret += name_1;
  72111. }
  72112. ret += "}";
  72113. }
  72114. return ret;
  72115. };
  72116. /**
  72117. * Get bone's index searching by name
  72118. * @param {string} name is bone's name to search for
  72119. * @return {number} Indice of the bone. Returns -1 if not found
  72120. */
  72121. Skeleton.prototype.getBoneIndexByName = function (name) {
  72122. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72123. if (this.bones[boneIndex].name === name) {
  72124. return boneIndex;
  72125. }
  72126. }
  72127. return -1;
  72128. };
  72129. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72130. // check name not already in use
  72131. if (!this._ranges[name]) {
  72132. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72133. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72134. if (this.bones[i].animations[0]) {
  72135. this.bones[i].animations[0].createRange(name, from, to);
  72136. }
  72137. }
  72138. }
  72139. };
  72140. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72141. if (deleteFrames === void 0) { deleteFrames = true; }
  72142. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72143. if (this.bones[i].animations[0]) {
  72144. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72145. }
  72146. }
  72147. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72148. };
  72149. Skeleton.prototype.getAnimationRange = function (name) {
  72150. return this._ranges[name];
  72151. };
  72152. /**
  72153. * Returns as an Array, all AnimationRanges defined on this skeleton
  72154. */
  72155. Skeleton.prototype.getAnimationRanges = function () {
  72156. var animationRanges = [];
  72157. var name;
  72158. var i = 0;
  72159. for (name in this._ranges) {
  72160. animationRanges[i] = this._ranges[name];
  72161. i++;
  72162. }
  72163. return animationRanges;
  72164. };
  72165. /**
  72166. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72167. */
  72168. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72169. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72170. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72171. return false;
  72172. }
  72173. var ret = true;
  72174. var frameOffset = this._getHighestAnimationFrame() + 1;
  72175. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72176. var boneDict = {};
  72177. var sourceBones = source.bones;
  72178. var nBones;
  72179. var i;
  72180. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72181. boneDict[sourceBones[i].name] = sourceBones[i];
  72182. }
  72183. if (this.bones.length !== sourceBones.length) {
  72184. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72185. ret = false;
  72186. }
  72187. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72188. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72189. var boneName = this.bones[i].name;
  72190. var sourceBone = boneDict[boneName];
  72191. if (sourceBone) {
  72192. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72193. }
  72194. else {
  72195. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72196. ret = false;
  72197. }
  72198. }
  72199. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72200. var range = source.getAnimationRange(name);
  72201. if (range) {
  72202. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72203. }
  72204. return ret;
  72205. };
  72206. Skeleton.prototype.returnToRest = function () {
  72207. for (var index = 0; index < this.bones.length; index++) {
  72208. this.bones[index].returnToRest();
  72209. }
  72210. };
  72211. Skeleton.prototype._getHighestAnimationFrame = function () {
  72212. var ret = 0;
  72213. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72214. if (this.bones[i].animations[0]) {
  72215. var highest = this.bones[i].animations[0].getHighestFrame();
  72216. if (ret < highest) {
  72217. ret = highest;
  72218. }
  72219. }
  72220. }
  72221. return ret;
  72222. };
  72223. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72224. var range = this.getAnimationRange(name);
  72225. if (!range) {
  72226. return null;
  72227. }
  72228. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72229. };
  72230. Skeleton.prototype._markAsDirty = function () {
  72231. this._isDirty = true;
  72232. };
  72233. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72234. this._meshesWithPoseMatrix.push(mesh);
  72235. };
  72236. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72237. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72238. if (index > -1) {
  72239. this._meshesWithPoseMatrix.splice(index, 1);
  72240. }
  72241. };
  72242. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72243. this.onBeforeComputeObservable.notifyObservers(this);
  72244. for (var index = 0; index < this.bones.length; index++) {
  72245. var bone = this.bones[index];
  72246. var parentBone = bone.getParent();
  72247. if (parentBone) {
  72248. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72249. }
  72250. else {
  72251. if (initialSkinMatrix) {
  72252. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72253. }
  72254. else {
  72255. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72256. }
  72257. }
  72258. if (bone._index !== -1) {
  72259. var mappedIndex = bone._index === null ? index : bone._index;
  72260. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72261. }
  72262. }
  72263. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72264. };
  72265. Skeleton.prototype.prepare = function () {
  72266. if (!this._isDirty) {
  72267. return;
  72268. }
  72269. if (this.needInitialSkinMatrix) {
  72270. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72271. var mesh = this._meshesWithPoseMatrix[index];
  72272. var poseMatrix = mesh.getPoseMatrix();
  72273. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72274. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72275. }
  72276. if (this._synchronizedWithMesh !== mesh) {
  72277. this._synchronizedWithMesh = mesh;
  72278. // Prepare bones
  72279. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72280. var bone = this.bones[boneIndex];
  72281. if (!bone.getParent()) {
  72282. var matrix = bone.getBaseMatrix();
  72283. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72284. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72285. }
  72286. }
  72287. }
  72288. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72289. }
  72290. }
  72291. else {
  72292. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72293. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72294. }
  72295. this._computeTransformMatrices(this._transformMatrices, null);
  72296. }
  72297. this._isDirty = false;
  72298. this._scene._activeBones.addCount(this.bones.length, false);
  72299. };
  72300. Skeleton.prototype.getAnimatables = function () {
  72301. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72302. this._animatables = [];
  72303. for (var index = 0; index < this.bones.length; index++) {
  72304. this._animatables.push(this.bones[index]);
  72305. }
  72306. }
  72307. return this._animatables;
  72308. };
  72309. Skeleton.prototype.clone = function (name, id) {
  72310. var result = new Skeleton(name, id || name, this._scene);
  72311. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72312. for (var index = 0; index < this.bones.length; index++) {
  72313. var source = this.bones[index];
  72314. var parentBone = null;
  72315. var parent_1 = source.getParent();
  72316. if (parent_1) {
  72317. var parentIndex = this.bones.indexOf(parent_1);
  72318. parentBone = result.bones[parentIndex];
  72319. }
  72320. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72321. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72322. }
  72323. if (this._ranges) {
  72324. result._ranges = {};
  72325. for (var rangeName in this._ranges) {
  72326. var range = this._ranges[rangeName];
  72327. if (range) {
  72328. result._ranges[rangeName] = range.clone();
  72329. }
  72330. }
  72331. }
  72332. this._isDirty = true;
  72333. return result;
  72334. };
  72335. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72336. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72337. this.bones.forEach(function (bone) {
  72338. bone.animations.forEach(function (animation) {
  72339. animation.enableBlending = true;
  72340. animation.blendingSpeed = blendingSpeed;
  72341. });
  72342. });
  72343. };
  72344. Skeleton.prototype.dispose = function () {
  72345. this._meshesWithPoseMatrix = [];
  72346. // Animations
  72347. this.getScene().stopAnimation(this);
  72348. // Remove from scene
  72349. this.getScene().removeSkeleton(this);
  72350. };
  72351. Skeleton.prototype.serialize = function () {
  72352. var serializationObject = {};
  72353. serializationObject.name = this.name;
  72354. serializationObject.id = this.id;
  72355. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72356. serializationObject.bones = [];
  72357. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72358. for (var index = 0; index < this.bones.length; index++) {
  72359. var bone = this.bones[index];
  72360. var parent_2 = bone.getParent();
  72361. var serializedBone = {
  72362. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72363. name: bone.name,
  72364. matrix: bone.getBaseMatrix().toArray(),
  72365. rest: bone.getRestPose().toArray()
  72366. };
  72367. serializationObject.bones.push(serializedBone);
  72368. if (bone.length) {
  72369. serializedBone.length = bone.length;
  72370. }
  72371. if (bone.animations && bone.animations.length > 0) {
  72372. serializedBone.animation = bone.animations[0].serialize();
  72373. }
  72374. serializationObject.ranges = [];
  72375. for (var name in this._ranges) {
  72376. var source = this._ranges[name];
  72377. if (!source) {
  72378. continue;
  72379. }
  72380. var range = {};
  72381. range.name = name;
  72382. range.from = source.from;
  72383. range.to = source.to;
  72384. serializationObject.ranges.push(range);
  72385. }
  72386. }
  72387. return serializationObject;
  72388. };
  72389. Skeleton.Parse = function (parsedSkeleton, scene) {
  72390. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72391. if (parsedSkeleton.dimensionsAtRest) {
  72392. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72393. }
  72394. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72395. var index;
  72396. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72397. var parsedBone = parsedSkeleton.bones[index];
  72398. var parentBone = null;
  72399. if (parsedBone.parentBoneIndex > -1) {
  72400. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72401. }
  72402. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72403. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72404. if (parsedBone.length) {
  72405. bone.length = parsedBone.length;
  72406. }
  72407. if (parsedBone.animation) {
  72408. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72409. }
  72410. }
  72411. // placed after bones, so createAnimationRange can cascade down
  72412. if (parsedSkeleton.ranges) {
  72413. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72414. var data = parsedSkeleton.ranges[index];
  72415. skeleton.createAnimationRange(data.name, data.from, data.to);
  72416. }
  72417. }
  72418. return skeleton;
  72419. };
  72420. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72421. if (forceUpdate === void 0) { forceUpdate = false; }
  72422. var renderId = this._scene.getRenderId();
  72423. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72424. this.bones[0].computeAbsoluteTransforms();
  72425. this._lastAbsoluteTransformsUpdateId = renderId;
  72426. }
  72427. };
  72428. Skeleton.prototype.getPoseMatrix = function () {
  72429. var poseMatrix = null;
  72430. if (this._meshesWithPoseMatrix.length > 0) {
  72431. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72432. }
  72433. return poseMatrix;
  72434. };
  72435. Skeleton.prototype.sortBones = function () {
  72436. var bones = new Array();
  72437. var visited = new Array(this.bones.length);
  72438. for (var index = 0; index < this.bones.length; index++) {
  72439. this._sortBones(index, bones, visited);
  72440. }
  72441. this.bones = bones;
  72442. };
  72443. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72444. if (visited[index]) {
  72445. return;
  72446. }
  72447. visited[index] = true;
  72448. var bone = this.bones[index];
  72449. if (bone._index === undefined) {
  72450. bone._index = index;
  72451. }
  72452. var parentBone = bone.getParent();
  72453. if (parentBone) {
  72454. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72455. }
  72456. bones.push(bone);
  72457. };
  72458. return Skeleton;
  72459. }());
  72460. BABYLON.Skeleton = Skeleton;
  72461. })(BABYLON || (BABYLON = {}));
  72462. //# sourceMappingURL=babylon.skeleton.js.map
  72463. var BABYLON;
  72464. (function (BABYLON) {
  72465. var SphericalPolynomial = /** @class */ (function () {
  72466. function SphericalPolynomial() {
  72467. this.x = BABYLON.Vector3.Zero();
  72468. this.y = BABYLON.Vector3.Zero();
  72469. this.z = BABYLON.Vector3.Zero();
  72470. this.xx = BABYLON.Vector3.Zero();
  72471. this.yy = BABYLON.Vector3.Zero();
  72472. this.zz = BABYLON.Vector3.Zero();
  72473. this.xy = BABYLON.Vector3.Zero();
  72474. this.yz = BABYLON.Vector3.Zero();
  72475. this.zx = BABYLON.Vector3.Zero();
  72476. }
  72477. SphericalPolynomial.prototype.addAmbient = function (color) {
  72478. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72479. this.xx = this.xx.add(colorVector);
  72480. this.yy = this.yy.add(colorVector);
  72481. this.zz = this.zz.add(colorVector);
  72482. };
  72483. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72484. var result = new SphericalPolynomial();
  72485. result.x = harmonics.L11.scale(1.02333);
  72486. result.y = harmonics.L1_1.scale(1.02333);
  72487. result.z = harmonics.L10.scale(1.02333);
  72488. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72489. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72490. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72491. result.yz = harmonics.L2_1.scale(0.858086);
  72492. result.zx = harmonics.L21.scale(0.858086);
  72493. result.xy = harmonics.L2_2.scale(0.858086);
  72494. result.scale(1.0 / Math.PI);
  72495. return result;
  72496. };
  72497. SphericalPolynomial.prototype.scale = function (scale) {
  72498. this.x = this.x.scale(scale);
  72499. this.y = this.y.scale(scale);
  72500. this.z = this.z.scale(scale);
  72501. this.xx = this.xx.scale(scale);
  72502. this.yy = this.yy.scale(scale);
  72503. this.zz = this.zz.scale(scale);
  72504. this.yz = this.yz.scale(scale);
  72505. this.zx = this.zx.scale(scale);
  72506. this.xy = this.xy.scale(scale);
  72507. };
  72508. return SphericalPolynomial;
  72509. }());
  72510. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72511. var SphericalHarmonics = /** @class */ (function () {
  72512. function SphericalHarmonics() {
  72513. this.L00 = BABYLON.Vector3.Zero();
  72514. this.L1_1 = BABYLON.Vector3.Zero();
  72515. this.L10 = BABYLON.Vector3.Zero();
  72516. this.L11 = BABYLON.Vector3.Zero();
  72517. this.L2_2 = BABYLON.Vector3.Zero();
  72518. this.L2_1 = BABYLON.Vector3.Zero();
  72519. this.L20 = BABYLON.Vector3.Zero();
  72520. this.L21 = BABYLON.Vector3.Zero();
  72521. this.L22 = BABYLON.Vector3.Zero();
  72522. }
  72523. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72524. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72525. var c = colorVector.scale(deltaSolidAngle);
  72526. this.L00 = this.L00.add(c.scale(0.282095));
  72527. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72528. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72529. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72530. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72531. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72532. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72533. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72534. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72535. };
  72536. SphericalHarmonics.prototype.scale = function (scale) {
  72537. this.L00 = this.L00.scale(scale);
  72538. this.L1_1 = this.L1_1.scale(scale);
  72539. this.L10 = this.L10.scale(scale);
  72540. this.L11 = this.L11.scale(scale);
  72541. this.L2_2 = this.L2_2.scale(scale);
  72542. this.L2_1 = this.L2_1.scale(scale);
  72543. this.L20 = this.L20.scale(scale);
  72544. this.L21 = this.L21.scale(scale);
  72545. this.L22 = this.L22.scale(scale);
  72546. };
  72547. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72548. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72549. //
  72550. // E_lm = A_l * L_lm
  72551. //
  72552. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72553. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72554. // the scaling factors are given in equation 9.
  72555. // Constant (Band 0)
  72556. this.L00 = this.L00.scale(3.141593);
  72557. // Linear (Band 1)
  72558. this.L1_1 = this.L1_1.scale(2.094395);
  72559. this.L10 = this.L10.scale(2.094395);
  72560. this.L11 = this.L11.scale(2.094395);
  72561. // Quadratic (Band 2)
  72562. this.L2_2 = this.L2_2.scale(0.785398);
  72563. this.L2_1 = this.L2_1.scale(0.785398);
  72564. this.L20 = this.L20.scale(0.785398);
  72565. this.L21 = this.L21.scale(0.785398);
  72566. this.L22 = this.L22.scale(0.785398);
  72567. };
  72568. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72569. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72570. // L = (1/pi) * E * rho
  72571. //
  72572. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72573. this.scale(1.0 / Math.PI);
  72574. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72575. // (The pixel shader must apply albedo after texture fetches, etc).
  72576. };
  72577. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72578. var result = new SphericalHarmonics();
  72579. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72580. result.L1_1 = polynomial.y.scale(0.977204);
  72581. result.L10 = polynomial.z.scale(0.977204);
  72582. result.L11 = polynomial.x.scale(0.977204);
  72583. result.L2_2 = polynomial.xy.scale(1.16538);
  72584. result.L2_1 = polynomial.yz.scale(1.16538);
  72585. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72586. result.L21 = polynomial.zx.scale(1.16538);
  72587. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72588. result.scale(Math.PI);
  72589. return result;
  72590. };
  72591. return SphericalHarmonics;
  72592. }());
  72593. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72594. })(BABYLON || (BABYLON = {}));
  72595. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72596. var BABYLON;
  72597. (function (BABYLON) {
  72598. var FileFaceOrientation = /** @class */ (function () {
  72599. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72600. this.name = name;
  72601. this.worldAxisForNormal = worldAxisForNormal;
  72602. this.worldAxisForFileX = worldAxisForFileX;
  72603. this.worldAxisForFileY = worldAxisForFileY;
  72604. }
  72605. return FileFaceOrientation;
  72606. }());
  72607. ;
  72608. /**
  72609. * Helper class dealing with the extraction of spherical polynomial dataArray
  72610. * from a cube map.
  72611. */
  72612. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72613. function CubeMapToSphericalPolynomialTools() {
  72614. }
  72615. /**
  72616. * Converts a texture to the according Spherical Polynomial data.
  72617. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72618. *
  72619. * @param texture The texture to extract the information from.
  72620. * @return The Spherical Polynomial data.
  72621. */
  72622. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72623. if (!texture.isCube) {
  72624. // Only supports cube Textures currently.
  72625. return null;
  72626. }
  72627. var size = texture.getSize().width;
  72628. var right = texture.readPixels(0);
  72629. var left = texture.readPixels(1);
  72630. var up;
  72631. var down;
  72632. if (texture.isRenderTarget) {
  72633. up = texture.readPixels(3);
  72634. down = texture.readPixels(2);
  72635. }
  72636. else {
  72637. up = texture.readPixels(2);
  72638. down = texture.readPixels(3);
  72639. }
  72640. var front = texture.readPixels(4);
  72641. var back = texture.readPixels(5);
  72642. var gammaSpace = texture.gammaSpace;
  72643. // Always read as RGBA.
  72644. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72645. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72646. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72647. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72648. }
  72649. var cubeInfo = {
  72650. size: size,
  72651. right: right,
  72652. left: left,
  72653. up: up,
  72654. down: down,
  72655. front: front,
  72656. back: back,
  72657. format: format,
  72658. type: type,
  72659. gammaSpace: gammaSpace,
  72660. };
  72661. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72662. };
  72663. /**
  72664. * Converts a cubemap to the according Spherical Polynomial data.
  72665. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72666. *
  72667. * @param cubeInfo The Cube map to extract the information from.
  72668. * @return The Spherical Polynomial data.
  72669. */
  72670. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72671. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72672. var totalSolidAngle = 0.0;
  72673. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72674. var du = 2.0 / cubeInfo.size;
  72675. var dv = du;
  72676. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72677. var minUV = du * 0.5 - 1.0;
  72678. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72679. var fileFace = this.FileFaces[faceIndex];
  72680. var dataArray = cubeInfo[fileFace.name];
  72681. var v = minUV;
  72682. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72683. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72684. // Because SP is still linear, so summation is fine in that basis.
  72685. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72686. for (var y = 0; y < cubeInfo.size; y++) {
  72687. var u = minUV;
  72688. for (var x = 0; x < cubeInfo.size; x++) {
  72689. // World direction (not normalised)
  72690. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72691. worldDirection.normalize();
  72692. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72693. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72694. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72695. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72696. // Handle Integer types.
  72697. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72698. r /= 255;
  72699. g /= 255;
  72700. b /= 255;
  72701. }
  72702. // Handle Gamma space textures.
  72703. if (cubeInfo.gammaSpace) {
  72704. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72705. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72706. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72707. }
  72708. var color = new BABYLON.Color3(r, g, b);
  72709. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72710. totalSolidAngle += deltaSolidAngle;
  72711. u += du;
  72712. }
  72713. v += dv;
  72714. }
  72715. }
  72716. // Solid angle for entire sphere is 4*pi
  72717. var sphereSolidAngle = 4.0 * Math.PI;
  72718. // Adjust the solid angle to allow for how many faces we processed.
  72719. var facesProcessed = 6.0;
  72720. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72721. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72722. // This is needed because the numerical integration over the cube uses a
  72723. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72724. // and also to compensate for accumulative error due to float precision in the summation.
  72725. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72726. sphericalHarmonics.scale(correctionFactor);
  72727. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72728. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72729. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72730. };
  72731. CubeMapToSphericalPolynomialTools.FileFaces = [
  72732. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72733. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72734. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72735. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72736. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72737. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72738. ];
  72739. return CubeMapToSphericalPolynomialTools;
  72740. }());
  72741. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72742. })(BABYLON || (BABYLON = {}));
  72743. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72744. var BABYLON;
  72745. (function (BABYLON) {
  72746. /**
  72747. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72748. */
  72749. var PanoramaToCubeMapTools = /** @class */ (function () {
  72750. function PanoramaToCubeMapTools() {
  72751. }
  72752. /**
  72753. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72754. *
  72755. * @param float32Array The source data.
  72756. * @param inputWidth The width of the input panorama.
  72757. * @param inputhHeight The height of the input panorama.
  72758. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72759. * @return The cubemap data
  72760. */
  72761. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72762. if (!float32Array) {
  72763. throw "ConvertPanoramaToCubemap: input cannot be null";
  72764. }
  72765. if (float32Array.length != inputWidth * inputHeight * 3) {
  72766. throw "ConvertPanoramaToCubemap: input size is wrong";
  72767. }
  72768. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72769. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72770. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72771. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72772. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72773. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72774. return {
  72775. front: textureFront,
  72776. back: textureBack,
  72777. left: textureLeft,
  72778. right: textureRight,
  72779. up: textureUp,
  72780. down: textureDown,
  72781. size: size,
  72782. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72783. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72784. gammaSpace: false,
  72785. };
  72786. };
  72787. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72788. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72789. var textureArray = new Float32Array(buffer);
  72790. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72791. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72792. var dy = 1 / texSize;
  72793. var fy = 0;
  72794. for (var y = 0; y < texSize; y++) {
  72795. var xv1 = faceData[0];
  72796. var xv2 = faceData[2];
  72797. for (var x = 0; x < texSize; x++) {
  72798. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72799. v.normalize();
  72800. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72801. // 3 channels per pixels
  72802. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72803. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72804. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72805. xv1 = xv1.add(rotDX1);
  72806. xv2 = xv2.add(rotDX2);
  72807. }
  72808. fy += dy;
  72809. }
  72810. return textureArray;
  72811. };
  72812. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72813. var theta = Math.atan2(vDir.z, vDir.x);
  72814. var phi = Math.acos(vDir.y);
  72815. while (theta < -Math.PI)
  72816. theta += 2 * Math.PI;
  72817. while (theta > Math.PI)
  72818. theta -= 2 * Math.PI;
  72819. var dx = theta / Math.PI;
  72820. var dy = phi / Math.PI;
  72821. // recenter.
  72822. dx = dx * 0.5 + 0.5;
  72823. var px = Math.round(dx * inputWidth);
  72824. if (px < 0)
  72825. px = 0;
  72826. else if (px >= inputWidth)
  72827. px = inputWidth - 1;
  72828. var py = Math.round(dy * inputHeight);
  72829. if (py < 0)
  72830. py = 0;
  72831. else if (py >= inputHeight)
  72832. py = inputHeight - 1;
  72833. var inputY = (inputHeight - py - 1);
  72834. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72835. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72836. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72837. return {
  72838. r: r,
  72839. g: g,
  72840. b: b
  72841. };
  72842. };
  72843. PanoramaToCubeMapTools.FACE_FRONT = [
  72844. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72845. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72846. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72847. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72848. ];
  72849. PanoramaToCubeMapTools.FACE_BACK = [
  72850. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72851. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72852. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72853. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72854. ];
  72855. PanoramaToCubeMapTools.FACE_RIGHT = [
  72856. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72857. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72858. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72859. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72860. ];
  72861. PanoramaToCubeMapTools.FACE_LEFT = [
  72862. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72863. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72864. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72865. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72866. ];
  72867. PanoramaToCubeMapTools.FACE_DOWN = [
  72868. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72869. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72870. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72871. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72872. ];
  72873. PanoramaToCubeMapTools.FACE_UP = [
  72874. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72875. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72876. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72877. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72878. ];
  72879. return PanoramaToCubeMapTools;
  72880. }());
  72881. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72882. })(BABYLON || (BABYLON = {}));
  72883. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72884. var BABYLON;
  72885. (function (BABYLON) {
  72886. ;
  72887. /**
  72888. * This groups tools to convert HDR texture to native colors array.
  72889. */
  72890. var HDRTools = /** @class */ (function () {
  72891. function HDRTools() {
  72892. }
  72893. HDRTools.Ldexp = function (mantissa, exponent) {
  72894. if (exponent > 1023) {
  72895. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72896. }
  72897. if (exponent < -1074) {
  72898. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72899. }
  72900. return mantissa * Math.pow(2, exponent);
  72901. };
  72902. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72903. if (exponent > 0) {
  72904. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72905. float32array[index + 0] = red * exponent;
  72906. float32array[index + 1] = green * exponent;
  72907. float32array[index + 2] = blue * exponent;
  72908. }
  72909. else {
  72910. float32array[index + 0] = 0;
  72911. float32array[index + 1] = 0;
  72912. float32array[index + 2] = 0;
  72913. }
  72914. };
  72915. HDRTools.readStringLine = function (uint8array, startIndex) {
  72916. var line = "";
  72917. var character = "";
  72918. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72919. character = String.fromCharCode(uint8array[i]);
  72920. if (character == "\n") {
  72921. break;
  72922. }
  72923. line += character;
  72924. }
  72925. return line;
  72926. };
  72927. /**
  72928. * Reads header information from an RGBE texture stored in a native array.
  72929. * More information on this format are available here:
  72930. * https://en.wikipedia.org/wiki/RGBE_image_format
  72931. *
  72932. * @param uint8array The binary file stored in native array.
  72933. * @return The header information.
  72934. */
  72935. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72936. var height = 0;
  72937. var width = 0;
  72938. var line = this.readStringLine(uint8array, 0);
  72939. if (line[0] != '#' || line[1] != '?') {
  72940. throw "Bad HDR Format.";
  72941. }
  72942. var endOfHeader = false;
  72943. var findFormat = false;
  72944. var lineIndex = 0;
  72945. do {
  72946. lineIndex += (line.length + 1);
  72947. line = this.readStringLine(uint8array, lineIndex);
  72948. if (line == "FORMAT=32-bit_rle_rgbe") {
  72949. findFormat = true;
  72950. }
  72951. else if (line.length == 0) {
  72952. endOfHeader = true;
  72953. }
  72954. } while (!endOfHeader);
  72955. if (!findFormat) {
  72956. throw "HDR Bad header format, unsupported FORMAT";
  72957. }
  72958. lineIndex += (line.length + 1);
  72959. line = this.readStringLine(uint8array, lineIndex);
  72960. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72961. var match = sizeRegexp.exec(line);
  72962. // TODO. Support +Y and -X if needed.
  72963. if (!match || match.length < 3) {
  72964. throw "HDR Bad header format, no size";
  72965. }
  72966. width = parseInt(match[2]);
  72967. height = parseInt(match[1]);
  72968. if (width < 8 || width > 0x7fff) {
  72969. throw "HDR Bad header format, unsupported size";
  72970. }
  72971. lineIndex += (line.length + 1);
  72972. return {
  72973. height: height,
  72974. width: width,
  72975. dataPosition: lineIndex
  72976. };
  72977. };
  72978. /**
  72979. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72980. * This RGBE texture needs to store the information as a panorama.
  72981. *
  72982. * More information on this format are available here:
  72983. * https://en.wikipedia.org/wiki/RGBE_image_format
  72984. *
  72985. * @param buffer The binary file stored in an array buffer.
  72986. * @param size The expected size of the extracted cubemap.
  72987. * @return The Cube Map information.
  72988. */
  72989. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72990. var uint8array = new Uint8Array(buffer);
  72991. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72992. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72993. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72994. return cubeMapData;
  72995. };
  72996. /**
  72997. * Returns the pixels data extracted from an RGBE texture.
  72998. * This pixels will be stored left to right up to down in the R G B order in one array.
  72999. *
  73000. * More information on this format are available here:
  73001. * https://en.wikipedia.org/wiki/RGBE_image_format
  73002. *
  73003. * @param uint8array The binary file stored in an array buffer.
  73004. * @param hdrInfo The header information of the file.
  73005. * @return The pixels data in RGB right to left up to down order.
  73006. */
  73007. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73008. // Keep for multi format supports.
  73009. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73010. };
  73011. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73012. var num_scanlines = hdrInfo.height;
  73013. var scanline_width = hdrInfo.width;
  73014. var a, b, c, d, count;
  73015. var dataIndex = hdrInfo.dataPosition;
  73016. var index = 0, endIndex = 0, i = 0;
  73017. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73018. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73019. // 3 channels of 4 bytes per pixel in float.
  73020. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73021. var resultArray = new Float32Array(resultBuffer);
  73022. // read in each successive scanline
  73023. while (num_scanlines > 0) {
  73024. a = uint8array[dataIndex++];
  73025. b = uint8array[dataIndex++];
  73026. c = uint8array[dataIndex++];
  73027. d = uint8array[dataIndex++];
  73028. if (a != 2 || b != 2 || (c & 0x80)) {
  73029. // this file is not run length encoded
  73030. throw "HDR Bad header format, not RLE";
  73031. }
  73032. if (((c << 8) | d) != scanline_width) {
  73033. throw "HDR Bad header format, wrong scan line width";
  73034. }
  73035. index = 0;
  73036. // read each of the four channels for the scanline into the buffer
  73037. for (i = 0; i < 4; i++) {
  73038. endIndex = (i + 1) * scanline_width;
  73039. while (index < endIndex) {
  73040. a = uint8array[dataIndex++];
  73041. b = uint8array[dataIndex++];
  73042. if (a > 128) {
  73043. // a run of the same value
  73044. count = a - 128;
  73045. if ((count == 0) || (count > endIndex - index)) {
  73046. throw "HDR Bad Format, bad scanline data (run)";
  73047. }
  73048. while (count-- > 0) {
  73049. scanLineArray[index++] = b;
  73050. }
  73051. }
  73052. else {
  73053. // a non-run
  73054. count = a;
  73055. if ((count == 0) || (count > endIndex - index)) {
  73056. throw "HDR Bad Format, bad scanline data (non-run)";
  73057. }
  73058. scanLineArray[index++] = b;
  73059. if (--count > 0) {
  73060. for (var j = 0; j < count; j++) {
  73061. scanLineArray[index++] = uint8array[dataIndex++];
  73062. }
  73063. }
  73064. }
  73065. }
  73066. }
  73067. // now convert data from buffer into floats
  73068. for (i = 0; i < scanline_width; i++) {
  73069. a = scanLineArray[i];
  73070. b = scanLineArray[i + scanline_width];
  73071. c = scanLineArray[i + 2 * scanline_width];
  73072. d = scanLineArray[i + 3 * scanline_width];
  73073. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73074. }
  73075. num_scanlines--;
  73076. }
  73077. return resultArray;
  73078. };
  73079. return HDRTools;
  73080. }());
  73081. BABYLON.HDRTools = HDRTools;
  73082. })(BABYLON || (BABYLON = {}));
  73083. //# sourceMappingURL=babylon.hdr.js.map
  73084. var BABYLON;
  73085. (function (BABYLON) {
  73086. /**
  73087. * This represents a texture coming from an HDR input.
  73088. *
  73089. * The only supported format is currently panorama picture stored in RGBE format.
  73090. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73091. */
  73092. var HDRCubeTexture = /** @class */ (function (_super) {
  73093. __extends(HDRCubeTexture, _super);
  73094. /**
  73095. * Instantiates an HDRTexture from the following parameters.
  73096. *
  73097. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73098. * @param scene The scene the texture will be used in
  73099. * @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.
  73100. * @param noMipmap Forces to not generate the mipmap if true
  73101. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73102. * @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)
  73103. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73104. */
  73105. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73106. if (noMipmap === void 0) { noMipmap = false; }
  73107. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73108. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73109. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73110. if (onLoad === void 0) { onLoad = null; }
  73111. if (onError === void 0) { onError = null; }
  73112. var _this = _super.call(this, scene) || this;
  73113. _this._useInGammaSpace = false;
  73114. _this._generateHarmonics = true;
  73115. _this._isBABYLONPreprocessed = false;
  73116. _this._onLoad = null;
  73117. _this._onError = null;
  73118. /**
  73119. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73120. */
  73121. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73122. /**
  73123. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73124. * This is usefull at run time to apply the good shader.
  73125. */
  73126. _this.isPMREM = false;
  73127. _this._isBlocking = true;
  73128. /**
  73129. * Gets or sets the center of the bounding box associated with the cube texture
  73130. * It must define where the camera used to render the texture was set
  73131. */
  73132. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73133. if (!url) {
  73134. return _this;
  73135. }
  73136. _this.name = url;
  73137. _this.url = url;
  73138. _this.hasAlpha = false;
  73139. _this.isCube = true;
  73140. _this._textureMatrix = BABYLON.Matrix.Identity();
  73141. _this._onLoad = onLoad;
  73142. _this._onError = onError;
  73143. _this.gammaSpace = false;
  73144. var caps = scene.getEngine().getCaps();
  73145. if (size) {
  73146. _this._isBABYLONPreprocessed = false;
  73147. _this._noMipmap = noMipmap;
  73148. _this._size = size;
  73149. _this._useInGammaSpace = useInGammaSpace;
  73150. _this._usePMREMGenerator = usePMREMGenerator &&
  73151. caps.textureLOD &&
  73152. caps.textureFloat &&
  73153. !_this._useInGammaSpace;
  73154. }
  73155. else {
  73156. _this._isBABYLONPreprocessed = true;
  73157. _this._noMipmap = false;
  73158. _this._useInGammaSpace = false;
  73159. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73160. !_this._useInGammaSpace;
  73161. }
  73162. _this.isPMREM = _this._usePMREMGenerator;
  73163. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73164. if (!_this._texture) {
  73165. if (!scene.useDelayedTextureLoading) {
  73166. _this.loadTexture();
  73167. }
  73168. else {
  73169. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73170. }
  73171. }
  73172. return _this;
  73173. }
  73174. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73175. /**
  73176. * Gets wether or not the texture is blocking during loading.
  73177. */
  73178. get: function () {
  73179. return this._isBlocking;
  73180. },
  73181. /**
  73182. * Sets wether or not the texture is blocking during loading.
  73183. */
  73184. set: function (value) {
  73185. this._isBlocking = value;
  73186. },
  73187. enumerable: true,
  73188. configurable: true
  73189. });
  73190. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73191. get: function () {
  73192. return this._boundingBoxSize;
  73193. },
  73194. /**
  73195. * Gets or sets the size of the bounding box associated with the cube texture
  73196. * When defined, the cubemap will switch to local mode
  73197. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73198. * @example https://www.babylonjs-playground.com/#RNASML
  73199. */
  73200. set: function (value) {
  73201. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73202. return;
  73203. }
  73204. this._boundingBoxSize = value;
  73205. var scene = this.getScene();
  73206. if (scene) {
  73207. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73208. }
  73209. },
  73210. enumerable: true,
  73211. configurable: true
  73212. });
  73213. /**
  73214. * Occurs when the file is a preprocessed .babylon.hdr file.
  73215. */
  73216. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73217. var _this = this;
  73218. var mipLevels = 0;
  73219. var floatArrayView = null;
  73220. var scene = this.getScene();
  73221. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73222. var mips = new Array();
  73223. if (!floatArrayView) {
  73224. return mips;
  73225. }
  73226. var startIndex = 30;
  73227. for (var level = 0; level < mipLevels; level++) {
  73228. mips.push([]);
  73229. // Fill each pixel of the mip level.
  73230. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73231. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73232. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73233. mips[level].push(faceData);
  73234. startIndex += faceSize;
  73235. }
  73236. }
  73237. return mips;
  73238. } : null;
  73239. var callback = function (buffer) {
  73240. var scene = _this.getScene();
  73241. if (!scene) {
  73242. return null;
  73243. }
  73244. // Create Native Array Views
  73245. var intArrayView = new Int32Array(buffer);
  73246. floatArrayView = new Float32Array(buffer);
  73247. // Fill header.
  73248. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73249. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73250. // Update Texture Information.
  73251. if (!_this._texture) {
  73252. return null;
  73253. }
  73254. _this._texture.updateSize(_this._size, _this._size);
  73255. // Fill polynomial information.
  73256. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73257. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73258. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73259. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73260. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73261. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73262. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73263. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73264. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73265. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73266. _this.sphericalPolynomial = sphericalPolynomial;
  73267. // Fill pixel data.
  73268. mipLevels = intArrayView[29]; // Number of mip levels.
  73269. var startIndex = 30;
  73270. var data = [];
  73271. var faceSize = Math.pow(_this._size, 2) * 3;
  73272. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73273. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73274. startIndex += faceSize;
  73275. }
  73276. var results = [];
  73277. var byteArray = null;
  73278. // Push each faces.
  73279. for (var k = 0; k < 6; k++) {
  73280. var dataFace = null;
  73281. // To be deprecated.
  73282. if (version === 1) {
  73283. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73284. dataFace = data[j];
  73285. }
  73286. // If special cases.
  73287. if (!mipmapGenerator && dataFace) {
  73288. if (!scene.getEngine().getCaps().textureFloat) {
  73289. // 3 channels of 1 bytes per pixel in bytes.
  73290. var byteBuffer = new ArrayBuffer(faceSize);
  73291. byteArray = new Uint8Array(byteBuffer);
  73292. }
  73293. for (var i = 0; i < _this._size * _this._size; i++) {
  73294. // Put in gamma space if requested.
  73295. if (_this._useInGammaSpace) {
  73296. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73297. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73298. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73299. }
  73300. // Convert to int texture for fallback.
  73301. if (byteArray) {
  73302. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73303. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73304. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73305. // May use luminance instead if the result is not accurate.
  73306. var max = Math.max(Math.max(r, g), b);
  73307. if (max > 255) {
  73308. var scale = 255 / max;
  73309. r *= scale;
  73310. g *= scale;
  73311. b *= scale;
  73312. }
  73313. byteArray[(i * 3) + 0] = r;
  73314. byteArray[(i * 3) + 1] = g;
  73315. byteArray[(i * 3) + 2] = b;
  73316. }
  73317. }
  73318. }
  73319. // Fill the array accordingly.
  73320. if (byteArray) {
  73321. results.push(byteArray);
  73322. }
  73323. else {
  73324. results.push(dataFace);
  73325. }
  73326. }
  73327. return results;
  73328. };
  73329. if (scene) {
  73330. 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);
  73331. }
  73332. };
  73333. /**
  73334. * Occurs when the file is raw .hdr file.
  73335. */
  73336. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73337. var _this = this;
  73338. var callback = function (buffer) {
  73339. var scene = _this.getScene();
  73340. if (!scene) {
  73341. return null;
  73342. }
  73343. // Extract the raw linear data.
  73344. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73345. // Generate harmonics if needed.
  73346. if (_this._generateHarmonics) {
  73347. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73348. _this.sphericalPolynomial = sphericalPolynomial;
  73349. }
  73350. var results = [];
  73351. var byteArray = null;
  73352. // Push each faces.
  73353. for (var j = 0; j < 6; j++) {
  73354. // Create uintarray fallback.
  73355. if (!scene.getEngine().getCaps().textureFloat) {
  73356. // 3 channels of 1 bytes per pixel in bytes.
  73357. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73358. byteArray = new Uint8Array(byteBuffer);
  73359. }
  73360. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73361. // If special cases.
  73362. if (_this._useInGammaSpace || byteArray) {
  73363. for (var i = 0; i < _this._size * _this._size; i++) {
  73364. // Put in gamma space if requested.
  73365. if (_this._useInGammaSpace) {
  73366. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73367. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73368. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73369. }
  73370. // Convert to int texture for fallback.
  73371. if (byteArray) {
  73372. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73373. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73374. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73375. // May use luminance instead if the result is not accurate.
  73376. var max = Math.max(Math.max(r, g), b);
  73377. if (max > 255) {
  73378. var scale = 255 / max;
  73379. r *= scale;
  73380. g *= scale;
  73381. b *= scale;
  73382. }
  73383. byteArray[(i * 3) + 0] = r;
  73384. byteArray[(i * 3) + 1] = g;
  73385. byteArray[(i * 3) + 2] = b;
  73386. }
  73387. }
  73388. }
  73389. if (byteArray) {
  73390. results.push(byteArray);
  73391. }
  73392. else {
  73393. results.push(dataFace);
  73394. }
  73395. }
  73396. return results;
  73397. };
  73398. var mipmapGenerator = null;
  73399. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73400. // if (!this._noMipmap &&
  73401. // this._usePMREMGenerator) {
  73402. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73403. // // Custom setup of the generator matching with the PBR shader values.
  73404. // var generator = new BABYLON.PMREMGenerator(data,
  73405. // this._size,
  73406. // this._size,
  73407. // 0,
  73408. // 3,
  73409. // this.getScene().getEngine().getCaps().textureFloat,
  73410. // 2048,
  73411. // 0.25,
  73412. // false,
  73413. // true);
  73414. // return generator.filterCubeMap();
  73415. // };
  73416. // }
  73417. var scene = this.getScene();
  73418. if (scene) {
  73419. 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);
  73420. }
  73421. };
  73422. /**
  73423. * Starts the loading process of the texture.
  73424. */
  73425. HDRCubeTexture.prototype.loadTexture = function () {
  73426. if (this._isBABYLONPreprocessed) {
  73427. this.loadBabylonTexture();
  73428. }
  73429. else {
  73430. this.loadHDRTexture();
  73431. }
  73432. };
  73433. HDRCubeTexture.prototype.clone = function () {
  73434. var scene = this.getScene();
  73435. if (!scene) {
  73436. return this;
  73437. }
  73438. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73439. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73440. // Base texture
  73441. newTexture.level = this.level;
  73442. newTexture.wrapU = this.wrapU;
  73443. newTexture.wrapV = this.wrapV;
  73444. newTexture.coordinatesIndex = this.coordinatesIndex;
  73445. newTexture.coordinatesMode = this.coordinatesMode;
  73446. return newTexture;
  73447. };
  73448. // Methods
  73449. HDRCubeTexture.prototype.delayLoad = function () {
  73450. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73451. return;
  73452. }
  73453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73454. this._texture = this._getFromCache(this.url, this._noMipmap);
  73455. if (!this._texture) {
  73456. this.loadTexture();
  73457. }
  73458. };
  73459. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73460. return this._textureMatrix;
  73461. };
  73462. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73463. this._textureMatrix = value;
  73464. };
  73465. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73466. var texture = null;
  73467. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73468. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73469. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73470. texture.name = parsedTexture.name;
  73471. texture.hasAlpha = parsedTexture.hasAlpha;
  73472. texture.level = parsedTexture.level;
  73473. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73474. texture.isBlocking = parsedTexture.isBlocking;
  73475. }
  73476. if (texture) {
  73477. if (parsedTexture.boundingBoxPosition) {
  73478. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73479. }
  73480. if (parsedTexture.boundingBoxSize) {
  73481. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73482. }
  73483. }
  73484. return texture;
  73485. };
  73486. HDRCubeTexture.prototype.serialize = function () {
  73487. if (!this.name) {
  73488. return null;
  73489. }
  73490. var serializationObject = {};
  73491. serializationObject.name = this.name;
  73492. serializationObject.hasAlpha = this.hasAlpha;
  73493. serializationObject.isCube = true;
  73494. serializationObject.level = this.level;
  73495. serializationObject.size = this._size;
  73496. serializationObject.coordinatesMode = this.coordinatesMode;
  73497. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73498. serializationObject.generateHarmonics = this._generateHarmonics;
  73499. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73500. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73501. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73502. serializationObject.noMipmap = this._noMipmap;
  73503. serializationObject.isBlocking = this._isBlocking;
  73504. return serializationObject;
  73505. };
  73506. /**
  73507. * Saves as a file the data contained in the texture in a binary format.
  73508. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73509. * as the spherical used in the lighting.
  73510. * @param url The HDR file url.
  73511. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73512. * @param onError Method called if any error happens during download.
  73513. * @return The packed binary data.
  73514. */
  73515. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73516. if (onError === void 0) { onError = null; }
  73517. var callback = function (buffer) {
  73518. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73519. // Returns a URL you can use as a href.
  73520. var objUrl = window.URL.createObjectURL(data);
  73521. // Simulates a link to it and click to dowload.
  73522. var a = document.createElement("a");
  73523. document.body.appendChild(a);
  73524. a.style.display = "none";
  73525. a.href = objUrl;
  73526. a.download = "envmap.babylon.hdr";
  73527. a.click();
  73528. };
  73529. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73530. };
  73531. /**
  73532. * Serializes the data contained in the texture in a binary format.
  73533. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73534. * as the spherical used in the lighting.
  73535. * @param url The HDR file url.
  73536. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73537. * @param onError Method called if any error happens during download.
  73538. * @return The packed binary data.
  73539. */
  73540. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73541. if (onError === void 0) { onError = null; }
  73542. // Needs the url tho create the texture.
  73543. if (!url) {
  73544. return;
  73545. }
  73546. // Check Power of two size.
  73547. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73548. return;
  73549. }
  73550. // Coming Back in 3.x.
  73551. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73552. };
  73553. HDRCubeTexture._facesMapping = [
  73554. "right",
  73555. "left",
  73556. "up",
  73557. "down",
  73558. "front",
  73559. "back"
  73560. ];
  73561. return HDRCubeTexture;
  73562. }(BABYLON.BaseTexture));
  73563. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73564. })(BABYLON || (BABYLON = {}));
  73565. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73566. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73567. // Huge respect for a such great lib.
  73568. // Earcut license:
  73569. // Copyright (c) 2016, Mapbox
  73570. //
  73571. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73572. // with or without fee is hereby granted, provided that the above copyright notice
  73573. // and this permission notice appear in all copies.
  73574. //
  73575. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73576. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73577. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73578. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73579. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73580. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73581. // THIS SOFTWARE.
  73582. var Earcut;
  73583. (function (Earcut) {
  73584. /**
  73585. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73586. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73587. * @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).
  73588. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73589. */
  73590. function earcut(data, holeIndices, dim) {
  73591. dim = dim || 2;
  73592. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73593. if (!outerNode)
  73594. return triangles;
  73595. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73596. if (hasHoles)
  73597. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73598. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73599. if (data.length > 80 * dim) {
  73600. minX = maxX = data[0];
  73601. minY = maxY = data[1];
  73602. for (var i = dim; i < outerLen; i += dim) {
  73603. x = data[i];
  73604. y = data[i + 1];
  73605. if (x < minX)
  73606. minX = x;
  73607. if (y < minY)
  73608. minY = y;
  73609. if (x > maxX)
  73610. maxX = x;
  73611. if (y > maxY)
  73612. maxY = y;
  73613. }
  73614. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73615. size = Math.max(maxX - minX, maxY - minY);
  73616. }
  73617. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73618. return triangles;
  73619. }
  73620. Earcut.earcut = earcut;
  73621. var Node = /** @class */ (function () {
  73622. function Node(i, x, y) {
  73623. this.i = i;
  73624. this.x = x;
  73625. this.y = y;
  73626. this.prev = null;
  73627. this.next = null;
  73628. this.z = null;
  73629. this.prevZ = null;
  73630. this.nextZ = null;
  73631. this.steiner = false;
  73632. }
  73633. return Node;
  73634. }());
  73635. // create a circular doubly linked list from polygon points in the specified winding order
  73636. function linkedList(data, start, end, dim, clockwise) {
  73637. var i, last = null;
  73638. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73639. for (i = start; i < end; i += dim)
  73640. last = insertNode(i, data[i], data[i + 1], last);
  73641. }
  73642. else {
  73643. for (i = end - dim; i >= start; i -= dim)
  73644. last = insertNode(i, data[i], data[i + 1], last);
  73645. }
  73646. if (last && equals(last, last.next)) {
  73647. removeNode(last);
  73648. last = last.next;
  73649. }
  73650. return last;
  73651. }
  73652. // eliminate colinear or duplicate points
  73653. function filterPoints(start, end) {
  73654. if (!start)
  73655. return start;
  73656. if (!end)
  73657. end = start;
  73658. var p = start, again;
  73659. do {
  73660. again = false;
  73661. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73662. removeNode(p);
  73663. p = end = p.prev;
  73664. if (p === p.next)
  73665. return undefined;
  73666. again = true;
  73667. }
  73668. else {
  73669. p = p.next;
  73670. }
  73671. } while (again || p !== end);
  73672. return end;
  73673. }
  73674. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73675. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73676. if (!ear)
  73677. return;
  73678. // interlink polygon nodes in z-order
  73679. if (!pass && size)
  73680. indexCurve(ear, minX, minY, size);
  73681. var stop = ear, prev, next;
  73682. // iterate through ears, slicing them one by one
  73683. while (ear.prev !== ear.next) {
  73684. prev = ear.prev;
  73685. next = ear.next;
  73686. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73687. // cut off the triangle
  73688. triangles.push(prev.i / dim);
  73689. triangles.push(ear.i / dim);
  73690. triangles.push(next.i / dim);
  73691. removeNode(ear);
  73692. // skipping the next vertice leads to less sliver triangles
  73693. ear = next.next;
  73694. stop = next.next;
  73695. continue;
  73696. }
  73697. ear = next;
  73698. // if we looped through the whole remaining polygon and can't find any more ears
  73699. if (ear === stop) {
  73700. // try filtering points and slicing again
  73701. if (!pass) {
  73702. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73703. // if this didn't work, try curing all small self-intersections locally
  73704. }
  73705. else if (pass === 1) {
  73706. ear = cureLocalIntersections(ear, triangles, dim);
  73707. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73708. // as a last resort, try splitting the remaining polygon into two
  73709. }
  73710. else if (pass === 2) {
  73711. splitEarcut(ear, triangles, dim, minX, minY, size);
  73712. }
  73713. break;
  73714. }
  73715. }
  73716. }
  73717. // check whether a polygon node forms a valid ear with adjacent nodes
  73718. function isEar(ear) {
  73719. var a = ear.prev, b = ear, c = ear.next;
  73720. if (area(a, b, c) >= 0)
  73721. return false; // reflex, can't be an ear
  73722. // now make sure we don't have other points inside the potential ear
  73723. var p = ear.next.next;
  73724. while (p !== ear.prev) {
  73725. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73726. area(p.prev, p, p.next) >= 0)
  73727. return false;
  73728. p = p.next;
  73729. }
  73730. return true;
  73731. }
  73732. function isEarHashed(ear, minX, minY, size) {
  73733. var a = ear.prev, b = ear, c = ear.next;
  73734. if (area(a, b, c) >= 0)
  73735. return false; // reflex, can't be an ear
  73736. // triangle bbox; min & max are calculated like this for speed
  73737. 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);
  73738. // z-order range for the current triangle bbox;
  73739. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73740. // first look for points inside the triangle in increasing z-order
  73741. var p = ear.nextZ;
  73742. while (p && p.z <= maxZ) {
  73743. if (p !== ear.prev &&
  73744. p !== ear.next &&
  73745. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73746. area(p.prev, p, p.next) >= 0)
  73747. return false;
  73748. p = p.nextZ;
  73749. }
  73750. // then look for points in decreasing z-order
  73751. p = ear.prevZ;
  73752. while (p && p.z >= minZ) {
  73753. if (p !== ear.prev &&
  73754. p !== ear.next &&
  73755. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73756. area(p.prev, p, p.next) >= 0)
  73757. return false;
  73758. p = p.prevZ;
  73759. }
  73760. return true;
  73761. }
  73762. // go through all polygon nodes and cure small local self-intersections
  73763. function cureLocalIntersections(start, triangles, dim) {
  73764. var p = start;
  73765. do {
  73766. var a = p.prev, b = p.next.next;
  73767. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73768. triangles.push(a.i / dim);
  73769. triangles.push(p.i / dim);
  73770. triangles.push(b.i / dim);
  73771. // remove two nodes involved
  73772. removeNode(p);
  73773. removeNode(p.next);
  73774. p = start = b;
  73775. }
  73776. p = p.next;
  73777. } while (p !== start);
  73778. return p;
  73779. }
  73780. // try splitting polygon into two and triangulate them independently
  73781. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73782. // look for a valid diagonal that divides the polygon into two
  73783. var a = start;
  73784. do {
  73785. var b = a.next.next;
  73786. while (b !== a.prev) {
  73787. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73788. // split the polygon in two by the diagonal
  73789. var c = splitPolygon(a, b);
  73790. // filter colinear points around the cuts
  73791. a = filterPoints(a, a.next);
  73792. c = filterPoints(c, c.next);
  73793. // run earcut on each half
  73794. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73795. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73796. return;
  73797. }
  73798. b = b.next;
  73799. }
  73800. a = a.next;
  73801. } while (a !== start);
  73802. }
  73803. // link every hole into the outer loop, producing a single-ring polygon without holes
  73804. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73805. var queue = [], i, len, start, end, list;
  73806. for (i = 0, len = holeIndices.length; i < len; i++) {
  73807. start = holeIndices[i] * dim;
  73808. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73809. list = linkedList(data, start, end, dim, false);
  73810. if (list === list.next)
  73811. list.steiner = true;
  73812. queue.push(getLeftmost(list));
  73813. }
  73814. queue.sort(compareX);
  73815. // process holes from left to right
  73816. for (i = 0; i < queue.length; i++) {
  73817. eliminateHole(queue[i], outerNode);
  73818. outerNode = filterPoints(outerNode, outerNode.next);
  73819. }
  73820. return outerNode;
  73821. }
  73822. function compareX(a, b) {
  73823. return a.x - b.x;
  73824. }
  73825. // find a bridge between vertices that connects hole with an outer ring and and link it
  73826. function eliminateHole(hole, outerNode) {
  73827. outerNode = findHoleBridge(hole, outerNode);
  73828. if (outerNode) {
  73829. var b = splitPolygon(outerNode, hole);
  73830. filterPoints(b, b.next);
  73831. }
  73832. }
  73833. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73834. function findHoleBridge(hole, outerNode) {
  73835. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73836. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73837. // segment's endpoint with lesser x will be potential connection point
  73838. do {
  73839. if (hy <= p.y && hy >= p.next.y) {
  73840. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73841. if (x <= hx && x > qx) {
  73842. qx = x;
  73843. if (x === hx) {
  73844. if (hy === p.y)
  73845. return p;
  73846. if (hy === p.next.y)
  73847. return p.next;
  73848. }
  73849. m = p.x < p.next.x ? p : p.next;
  73850. }
  73851. }
  73852. p = p.next;
  73853. } while (p !== outerNode);
  73854. if (!m)
  73855. return null;
  73856. if (hx === qx)
  73857. return m.prev; // hole touches outer segment; pick lower endpoint
  73858. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73859. // if there are no points found, we have a valid connection;
  73860. // otherwise choose the point of the minimum angle with the ray as connection point
  73861. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73862. p = m.next;
  73863. while (p !== stop) {
  73864. if (hx >= p.x &&
  73865. p.x >= mx &&
  73866. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73867. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73868. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73869. m = p;
  73870. tanMin = tan;
  73871. }
  73872. }
  73873. p = p.next;
  73874. }
  73875. return m;
  73876. }
  73877. // interlink polygon nodes in z-order
  73878. function indexCurve(start, minX, minY, size) {
  73879. var p = start;
  73880. do {
  73881. if (p.z === null)
  73882. p.z = zOrder(p.x, p.y, minX, minY, size);
  73883. p.prevZ = p.prev;
  73884. p.nextZ = p.next;
  73885. p = p.next;
  73886. } while (p !== start);
  73887. p.prevZ.nextZ = null;
  73888. p.prevZ = null;
  73889. sortLinked(p);
  73890. }
  73891. // Simon Tatham's linked list merge sort algorithm
  73892. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73893. function sortLinked(list) {
  73894. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73895. do {
  73896. p = list;
  73897. list = null;
  73898. tail = null;
  73899. numMerges = 0;
  73900. while (p) {
  73901. numMerges++;
  73902. q = p;
  73903. pSize = 0;
  73904. for (i = 0; i < inSize; i++) {
  73905. pSize++;
  73906. q = q.nextZ;
  73907. if (!q)
  73908. break;
  73909. }
  73910. qSize = inSize;
  73911. while (pSize > 0 || (qSize > 0 && q)) {
  73912. if (pSize === 0) {
  73913. e = q;
  73914. q = q.nextZ;
  73915. qSize--;
  73916. }
  73917. else if (qSize === 0 || !q) {
  73918. e = p;
  73919. p = p.nextZ;
  73920. pSize--;
  73921. }
  73922. else if (p.z <= q.z) {
  73923. e = p;
  73924. p = p.nextZ;
  73925. pSize--;
  73926. }
  73927. else {
  73928. e = q;
  73929. q = q.nextZ;
  73930. qSize--;
  73931. }
  73932. if (tail)
  73933. tail.nextZ = e;
  73934. else
  73935. list = e;
  73936. e.prevZ = tail;
  73937. tail = e;
  73938. }
  73939. p = q;
  73940. }
  73941. tail.nextZ = null;
  73942. inSize *= 2;
  73943. } while (numMerges > 1);
  73944. return list;
  73945. }
  73946. // z-order of a point given coords and size of the data bounding box
  73947. function zOrder(x, y, minX, minY, size) {
  73948. // coords are transformed into non-negative 15-bit integer range
  73949. x = 32767 * (x - minX) / size;
  73950. y = 32767 * (y - minY) / size;
  73951. x = (x | (x << 8)) & 0x00FF00FF;
  73952. x = (x | (x << 4)) & 0x0F0F0F0F;
  73953. x = (x | (x << 2)) & 0x33333333;
  73954. x = (x | (x << 1)) & 0x55555555;
  73955. y = (y | (y << 8)) & 0x00FF00FF;
  73956. y = (y | (y << 4)) & 0x0F0F0F0F;
  73957. y = (y | (y << 2)) & 0x33333333;
  73958. y = (y | (y << 1)) & 0x55555555;
  73959. return x | (y << 1);
  73960. }
  73961. // find the leftmost node of a polygon ring
  73962. function getLeftmost(start) {
  73963. var p = start, leftmost = start;
  73964. do {
  73965. if (p.x < leftmost.x)
  73966. leftmost = p;
  73967. p = p.next;
  73968. } while (p !== start);
  73969. return leftmost;
  73970. }
  73971. // check if a point lies within a convex triangle
  73972. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73973. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73974. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73975. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73976. }
  73977. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73978. function isValidDiagonal(a, b) {
  73979. return a.next.i !== b.i &&
  73980. a.prev.i !== b.i &&
  73981. !intersectsPolygon(a, b) &&
  73982. locallyInside(a, b) &&
  73983. locallyInside(b, a) &&
  73984. middleInside(a, b);
  73985. }
  73986. // signed area of a triangle
  73987. function area(p, q, r) {
  73988. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73989. }
  73990. // check if two points are equal
  73991. function equals(p1, p2) {
  73992. return p1.x === p2.x && p1.y === p2.y;
  73993. }
  73994. // check if two segments intersect
  73995. function intersects(p1, q1, p2, q2) {
  73996. if ((equals(p1, q1) && equals(p2, q2)) ||
  73997. (equals(p1, q2) && equals(p2, q1)))
  73998. return true;
  73999. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74000. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74001. }
  74002. // check if a polygon diagonal intersects any polygon segments
  74003. function intersectsPolygon(a, b) {
  74004. var p = a;
  74005. do {
  74006. if (p.i !== a.i &&
  74007. p.next.i !== a.i &&
  74008. p.i !== b.i &&
  74009. p.next.i !== b.i &&
  74010. intersects(p, p.next, a, b))
  74011. return true;
  74012. p = p.next;
  74013. } while (p !== a);
  74014. return false;
  74015. }
  74016. // check if a polygon diagonal is locally inside the polygon
  74017. function locallyInside(a, b) {
  74018. return area(a.prev, a, a.next) < 0
  74019. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74020. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74021. }
  74022. // check if the middle point of a polygon diagonal is inside the polygon
  74023. function middleInside(a, b) {
  74024. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74025. do {
  74026. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74027. inside = !inside;
  74028. p = p.next;
  74029. } while (p !== a);
  74030. return inside;
  74031. }
  74032. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74033. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74034. function splitPolygon(a, b) {
  74035. 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;
  74036. a.next = b;
  74037. b.prev = a;
  74038. a2.next = an;
  74039. an.prev = a2;
  74040. b2.next = a2;
  74041. a2.prev = b2;
  74042. bp.next = b2;
  74043. b2.prev = bp;
  74044. return b2;
  74045. }
  74046. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74047. function insertNode(i, x, y, last) {
  74048. var p = new Node(i, x, y);
  74049. if (!last) {
  74050. p.prev = p;
  74051. p.next = p;
  74052. }
  74053. else {
  74054. p.next = last.next;
  74055. p.prev = last;
  74056. last.next.prev = p;
  74057. last.next = p;
  74058. }
  74059. return p;
  74060. }
  74061. function removeNode(p) {
  74062. p.next.prev = p.prev;
  74063. p.prev.next = p.next;
  74064. if (p.prevZ)
  74065. p.prevZ.nextZ = p.nextZ;
  74066. if (p.nextZ)
  74067. p.nextZ.prevZ = p.prevZ;
  74068. }
  74069. /**
  74070. * return a percentage difference between the polygon area and its triangulation area;
  74071. * used to verify correctness of triangulation
  74072. */
  74073. function deviation(data, holeIndices, dim, triangles) {
  74074. var hasHoles = holeIndices && holeIndices.length;
  74075. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74076. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74077. if (hasHoles) {
  74078. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74079. var start = holeIndices[i] * dim;
  74080. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74081. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74082. }
  74083. }
  74084. var trianglesArea = 0;
  74085. for (i = 0; i < triangles.length; i += 3) {
  74086. var a = triangles[i] * dim;
  74087. var b = triangles[i + 1] * dim;
  74088. var c = triangles[i + 2] * dim;
  74089. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74090. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74091. }
  74092. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74093. }
  74094. Earcut.deviation = deviation;
  74095. ;
  74096. function signedArea(data, start, end, dim) {
  74097. var sum = 0;
  74098. for (var i = start, j = end - dim; i < end; i += dim) {
  74099. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74100. j = i;
  74101. }
  74102. return sum;
  74103. }
  74104. /**
  74105. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74106. */
  74107. function flatten(data) {
  74108. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74109. for (var i = 0; i < data.length; i++) {
  74110. for (var j = 0; j < data[i].length; j++) {
  74111. for (var d = 0; d < dim; d++)
  74112. result.vertices.push(data[i][j][d]);
  74113. }
  74114. if (i > 0) {
  74115. holeIndex += data[i - 1].length;
  74116. result.holes.push(holeIndex);
  74117. }
  74118. }
  74119. return result;
  74120. }
  74121. Earcut.flatten = flatten;
  74122. ;
  74123. })(Earcut || (Earcut = {}));
  74124. //# sourceMappingURL=babylon.earcut.js.map
  74125. var BABYLON;
  74126. (function (BABYLON) {
  74127. var IndexedVector2 = /** @class */ (function (_super) {
  74128. __extends(IndexedVector2, _super);
  74129. function IndexedVector2(original, index) {
  74130. var _this = _super.call(this, original.x, original.y) || this;
  74131. _this.index = index;
  74132. return _this;
  74133. }
  74134. return IndexedVector2;
  74135. }(BABYLON.Vector2));
  74136. var PolygonPoints = /** @class */ (function () {
  74137. function PolygonPoints() {
  74138. this.elements = new Array();
  74139. }
  74140. PolygonPoints.prototype.add = function (originalPoints) {
  74141. var _this = this;
  74142. var result = new Array();
  74143. originalPoints.forEach(function (point) {
  74144. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74145. var newPoint = new IndexedVector2(point, _this.elements.length);
  74146. result.push(newPoint);
  74147. _this.elements.push(newPoint);
  74148. }
  74149. });
  74150. return result;
  74151. };
  74152. PolygonPoints.prototype.computeBounds = function () {
  74153. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74154. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74155. this.elements.forEach(function (point) {
  74156. // x
  74157. if (point.x < lmin.x) {
  74158. lmin.x = point.x;
  74159. }
  74160. else if (point.x > lmax.x) {
  74161. lmax.x = point.x;
  74162. }
  74163. // y
  74164. if (point.y < lmin.y) {
  74165. lmin.y = point.y;
  74166. }
  74167. else if (point.y > lmax.y) {
  74168. lmax.y = point.y;
  74169. }
  74170. });
  74171. return {
  74172. min: lmin,
  74173. max: lmax,
  74174. width: lmax.x - lmin.x,
  74175. height: lmax.y - lmin.y
  74176. };
  74177. };
  74178. return PolygonPoints;
  74179. }());
  74180. var Polygon = /** @class */ (function () {
  74181. function Polygon() {
  74182. }
  74183. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74184. return [
  74185. new BABYLON.Vector2(xmin, ymin),
  74186. new BABYLON.Vector2(xmax, ymin),
  74187. new BABYLON.Vector2(xmax, ymax),
  74188. new BABYLON.Vector2(xmin, ymax)
  74189. ];
  74190. };
  74191. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74192. if (cx === void 0) { cx = 0; }
  74193. if (cy === void 0) { cy = 0; }
  74194. if (numberOfSides === void 0) { numberOfSides = 32; }
  74195. var result = new Array();
  74196. var angle = 0;
  74197. var increment = (Math.PI * 2) / numberOfSides;
  74198. for (var i = 0; i < numberOfSides; i++) {
  74199. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74200. angle -= increment;
  74201. }
  74202. return result;
  74203. };
  74204. Polygon.Parse = function (input) {
  74205. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74206. var i, result = [];
  74207. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74208. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74209. }
  74210. return result;
  74211. };
  74212. Polygon.StartingAt = function (x, y) {
  74213. return BABYLON.Path2.StartingAt(x, y);
  74214. };
  74215. return Polygon;
  74216. }());
  74217. BABYLON.Polygon = Polygon;
  74218. var PolygonMeshBuilder = /** @class */ (function () {
  74219. function PolygonMeshBuilder(name, contours, scene) {
  74220. this._points = new PolygonPoints();
  74221. this._outlinepoints = new PolygonPoints();
  74222. this._holes = new Array();
  74223. this._epoints = new Array();
  74224. this._eholes = new Array();
  74225. this._name = name;
  74226. this._scene = scene;
  74227. var points;
  74228. if (contours instanceof BABYLON.Path2) {
  74229. points = contours.getPoints();
  74230. }
  74231. else {
  74232. points = contours;
  74233. }
  74234. this._addToepoint(points);
  74235. this._points.add(points);
  74236. this._outlinepoints.add(points);
  74237. }
  74238. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74239. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74240. var p = points_1[_i];
  74241. this._epoints.push(p.x, p.y);
  74242. }
  74243. };
  74244. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74245. this._points.add(hole);
  74246. var holepoints = new PolygonPoints();
  74247. holepoints.add(hole);
  74248. this._holes.push(holepoints);
  74249. this._eholes.push(this._epoints.length / 2);
  74250. this._addToepoint(hole);
  74251. return this;
  74252. };
  74253. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74254. var _this = this;
  74255. if (updatable === void 0) { updatable = false; }
  74256. if (depth === void 0) { depth = 0; }
  74257. var result = new BABYLON.Mesh(this._name, this._scene);
  74258. var normals = new Array();
  74259. var positions = new Array();
  74260. var uvs = new Array();
  74261. var bounds = this._points.computeBounds();
  74262. this._points.elements.forEach(function (p) {
  74263. normals.push(0, 1.0, 0);
  74264. positions.push(p.x, 0, p.y);
  74265. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74266. });
  74267. var indices = new Array();
  74268. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74269. for (var i = 0; i < res.length; i++) {
  74270. indices.push(res[i]);
  74271. }
  74272. if (depth > 0) {
  74273. var positionscount = (positions.length / 3); //get the current pointcount
  74274. this._points.elements.forEach(function (p) {
  74275. normals.push(0, -1.0, 0);
  74276. positions.push(p.x, -depth, p.y);
  74277. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74278. });
  74279. var totalCount = indices.length;
  74280. for (var i = 0; i < totalCount; i += 3) {
  74281. var i0 = indices[i + 0];
  74282. var i1 = indices[i + 1];
  74283. var i2 = indices[i + 2];
  74284. indices.push(i2 + positionscount);
  74285. indices.push(i1 + positionscount);
  74286. indices.push(i0 + positionscount);
  74287. }
  74288. //Add the sides
  74289. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74290. this._holes.forEach(function (hole) {
  74291. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74292. });
  74293. }
  74294. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74295. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74296. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74297. result.setIndices(indices);
  74298. return result;
  74299. };
  74300. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74301. var StartIndex = positions.length / 3;
  74302. var ulength = 0;
  74303. for (var i = 0; i < points.elements.length; i++) {
  74304. var p = points.elements[i];
  74305. var p1;
  74306. if ((i + 1) > points.elements.length - 1) {
  74307. p1 = points.elements[0];
  74308. }
  74309. else {
  74310. p1 = points.elements[i + 1];
  74311. }
  74312. positions.push(p.x, 0, p.y);
  74313. positions.push(p.x, -depth, p.y);
  74314. positions.push(p1.x, 0, p1.y);
  74315. positions.push(p1.x, -depth, p1.y);
  74316. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74317. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74318. var v3 = v2.subtract(v1);
  74319. var v4 = new BABYLON.Vector3(0, 1, 0);
  74320. var vn = BABYLON.Vector3.Cross(v3, v4);
  74321. vn = vn.normalize();
  74322. uvs.push(ulength / bounds.width, 0);
  74323. uvs.push(ulength / bounds.width, 1);
  74324. ulength += v3.length();
  74325. uvs.push((ulength / bounds.width), 0);
  74326. uvs.push((ulength / bounds.width), 1);
  74327. if (!flip) {
  74328. normals.push(-vn.x, -vn.y, -vn.z);
  74329. normals.push(-vn.x, -vn.y, -vn.z);
  74330. normals.push(-vn.x, -vn.y, -vn.z);
  74331. normals.push(-vn.x, -vn.y, -vn.z);
  74332. indices.push(StartIndex);
  74333. indices.push(StartIndex + 1);
  74334. indices.push(StartIndex + 2);
  74335. indices.push(StartIndex + 1);
  74336. indices.push(StartIndex + 3);
  74337. indices.push(StartIndex + 2);
  74338. }
  74339. else {
  74340. normals.push(vn.x, vn.y, vn.z);
  74341. normals.push(vn.x, vn.y, vn.z);
  74342. normals.push(vn.x, vn.y, vn.z);
  74343. normals.push(vn.x, vn.y, vn.z);
  74344. indices.push(StartIndex);
  74345. indices.push(StartIndex + 2);
  74346. indices.push(StartIndex + 1);
  74347. indices.push(StartIndex + 1);
  74348. indices.push(StartIndex + 2);
  74349. indices.push(StartIndex + 3);
  74350. }
  74351. StartIndex += 4;
  74352. }
  74353. ;
  74354. };
  74355. return PolygonMeshBuilder;
  74356. }());
  74357. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74358. })(BABYLON || (BABYLON = {}));
  74359. //# sourceMappingURL=babylon.polygonMesh.js.map
  74360. var BABYLON;
  74361. (function (BABYLON) {
  74362. // Unique ID when we import meshes from Babylon to CSG
  74363. var currentCSGMeshId = 0;
  74364. // # class Vertex
  74365. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74366. // one to provide additional features like texture coordinates and vertex
  74367. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74368. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74369. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74370. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74371. // is not used anywhere else.
  74372. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74373. var Vertex = /** @class */ (function () {
  74374. function Vertex(pos, normal, uv) {
  74375. this.pos = pos;
  74376. this.normal = normal;
  74377. this.uv = uv;
  74378. }
  74379. Vertex.prototype.clone = function () {
  74380. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74381. };
  74382. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74383. // orientation of a polygon is flipped.
  74384. Vertex.prototype.flip = function () {
  74385. this.normal = this.normal.scale(-1);
  74386. };
  74387. // Create a new vertex between this vertex and `other` by linearly
  74388. // interpolating all properties using a parameter of `t`. Subclasses should
  74389. // override this to interpolate additional properties.
  74390. Vertex.prototype.interpolate = function (other, t) {
  74391. 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));
  74392. };
  74393. return Vertex;
  74394. }());
  74395. // # class Plane
  74396. // Represents a plane in 3D space.
  74397. var Plane = /** @class */ (function () {
  74398. function Plane(normal, w) {
  74399. this.normal = normal;
  74400. this.w = w;
  74401. }
  74402. Plane.FromPoints = function (a, b, c) {
  74403. var v0 = c.subtract(a);
  74404. var v1 = b.subtract(a);
  74405. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74406. return null;
  74407. }
  74408. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74409. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74410. };
  74411. Plane.prototype.clone = function () {
  74412. return new Plane(this.normal.clone(), this.w);
  74413. };
  74414. Plane.prototype.flip = function () {
  74415. this.normal.scaleInPlace(-1);
  74416. this.w = -this.w;
  74417. };
  74418. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74419. // fragments in the appropriate lists. Coplanar polygons go into either
  74420. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74421. // respect to this plane. Polygons in front or in back of this plane go into
  74422. // either `front` or `back`.
  74423. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74424. var COPLANAR = 0;
  74425. var FRONT = 1;
  74426. var BACK = 2;
  74427. var SPANNING = 3;
  74428. // Classify each point as well as the entire polygon into one of the above
  74429. // four classes.
  74430. var polygonType = 0;
  74431. var types = [];
  74432. var i;
  74433. var t;
  74434. for (i = 0; i < polygon.vertices.length; i++) {
  74435. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74436. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74437. polygonType |= type;
  74438. types.push(type);
  74439. }
  74440. // Put the polygon in the correct list, splitting it when necessary.
  74441. switch (polygonType) {
  74442. case COPLANAR:
  74443. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74444. break;
  74445. case FRONT:
  74446. front.push(polygon);
  74447. break;
  74448. case BACK:
  74449. back.push(polygon);
  74450. break;
  74451. case SPANNING:
  74452. var f = [], b = [];
  74453. for (i = 0; i < polygon.vertices.length; i++) {
  74454. var j = (i + 1) % polygon.vertices.length;
  74455. var ti = types[i], tj = types[j];
  74456. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74457. if (ti !== BACK)
  74458. f.push(vi);
  74459. if (ti !== FRONT)
  74460. b.push(ti !== BACK ? vi.clone() : vi);
  74461. if ((ti | tj) === SPANNING) {
  74462. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74463. var v = vi.interpolate(vj, t);
  74464. f.push(v);
  74465. b.push(v.clone());
  74466. }
  74467. }
  74468. var poly;
  74469. if (f.length >= 3) {
  74470. poly = new Polygon(f, polygon.shared);
  74471. if (poly.plane)
  74472. front.push(poly);
  74473. }
  74474. if (b.length >= 3) {
  74475. poly = new Polygon(b, polygon.shared);
  74476. if (poly.plane)
  74477. back.push(poly);
  74478. }
  74479. break;
  74480. }
  74481. };
  74482. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74483. // point is on the plane.
  74484. Plane.EPSILON = 1e-5;
  74485. return Plane;
  74486. }());
  74487. // # class Polygon
  74488. // Represents a convex polygon. The vertices used to initialize a polygon must
  74489. // be coplanar and form a convex loop.
  74490. //
  74491. // Each convex polygon has a `shared` property, which is shared between all
  74492. // polygons that are clones of each other or were split from the same polygon.
  74493. // This can be used to define per-polygon properties (such as surface color).
  74494. var Polygon = /** @class */ (function () {
  74495. function Polygon(vertices, shared) {
  74496. this.vertices = vertices;
  74497. this.shared = shared;
  74498. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74499. }
  74500. Polygon.prototype.clone = function () {
  74501. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74502. return new Polygon(vertices, this.shared);
  74503. };
  74504. Polygon.prototype.flip = function () {
  74505. this.vertices.reverse().map(function (v) { v.flip(); });
  74506. this.plane.flip();
  74507. };
  74508. return Polygon;
  74509. }());
  74510. // # class Node
  74511. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74512. // by picking a polygon to split along. That polygon (and all other coplanar
  74513. // polygons) are added directly to that node and the other polygons are added to
  74514. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74515. // no distinction between internal and leaf nodes.
  74516. var Node = /** @class */ (function () {
  74517. function Node(polygons) {
  74518. this.plane = null;
  74519. this.front = null;
  74520. this.back = null;
  74521. this.polygons = new Array();
  74522. if (polygons) {
  74523. this.build(polygons);
  74524. }
  74525. }
  74526. Node.prototype.clone = function () {
  74527. var node = new Node();
  74528. node.plane = this.plane && this.plane.clone();
  74529. node.front = this.front && this.front.clone();
  74530. node.back = this.back && this.back.clone();
  74531. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74532. return node;
  74533. };
  74534. // Convert solid space to empty space and empty space to solid space.
  74535. Node.prototype.invert = function () {
  74536. for (var i = 0; i < this.polygons.length; i++) {
  74537. this.polygons[i].flip();
  74538. }
  74539. if (this.plane) {
  74540. this.plane.flip();
  74541. }
  74542. if (this.front) {
  74543. this.front.invert();
  74544. }
  74545. if (this.back) {
  74546. this.back.invert();
  74547. }
  74548. var temp = this.front;
  74549. this.front = this.back;
  74550. this.back = temp;
  74551. };
  74552. // Recursively remove all polygons in `polygons` that are inside this BSP
  74553. // tree.
  74554. Node.prototype.clipPolygons = function (polygons) {
  74555. if (!this.plane)
  74556. return polygons.slice();
  74557. var front = new Array(), back = new Array();
  74558. for (var i = 0; i < polygons.length; i++) {
  74559. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74560. }
  74561. if (this.front) {
  74562. front = this.front.clipPolygons(front);
  74563. }
  74564. if (this.back) {
  74565. back = this.back.clipPolygons(back);
  74566. }
  74567. else {
  74568. back = [];
  74569. }
  74570. return front.concat(back);
  74571. };
  74572. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74573. // `bsp`.
  74574. Node.prototype.clipTo = function (bsp) {
  74575. this.polygons = bsp.clipPolygons(this.polygons);
  74576. if (this.front)
  74577. this.front.clipTo(bsp);
  74578. if (this.back)
  74579. this.back.clipTo(bsp);
  74580. };
  74581. // Return a list of all polygons in this BSP tree.
  74582. Node.prototype.allPolygons = function () {
  74583. var polygons = this.polygons.slice();
  74584. if (this.front)
  74585. polygons = polygons.concat(this.front.allPolygons());
  74586. if (this.back)
  74587. polygons = polygons.concat(this.back.allPolygons());
  74588. return polygons;
  74589. };
  74590. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74591. // new polygons are filtered down to the bottom of the tree and become new
  74592. // nodes there. Each set of polygons is partitioned using the first polygon
  74593. // (no heuristic is used to pick a good split).
  74594. Node.prototype.build = function (polygons) {
  74595. if (!polygons.length)
  74596. return;
  74597. if (!this.plane)
  74598. this.plane = polygons[0].plane.clone();
  74599. var front = new Array(), back = new Array();
  74600. for (var i = 0; i < polygons.length; i++) {
  74601. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74602. }
  74603. if (front.length) {
  74604. if (!this.front)
  74605. this.front = new Node();
  74606. this.front.build(front);
  74607. }
  74608. if (back.length) {
  74609. if (!this.back)
  74610. this.back = new Node();
  74611. this.back.build(back);
  74612. }
  74613. };
  74614. return Node;
  74615. }());
  74616. var CSG = /** @class */ (function () {
  74617. function CSG() {
  74618. this.polygons = new Array();
  74619. }
  74620. // Convert BABYLON.Mesh to BABYLON.CSG
  74621. CSG.FromMesh = function (mesh) {
  74622. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74623. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74624. if (mesh instanceof BABYLON.Mesh) {
  74625. mesh.computeWorldMatrix(true);
  74626. matrix = mesh.getWorldMatrix();
  74627. meshPosition = mesh.position.clone();
  74628. meshRotation = mesh.rotation.clone();
  74629. if (mesh.rotationQuaternion) {
  74630. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74631. }
  74632. meshScaling = mesh.scaling.clone();
  74633. }
  74634. else {
  74635. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74636. }
  74637. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74638. var subMeshes = mesh.subMeshes;
  74639. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74640. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74641. vertices = [];
  74642. for (var j = 0; j < 3; j++) {
  74643. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74644. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74645. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74646. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74647. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74648. vertex = new Vertex(position, normal, uv);
  74649. vertices.push(vertex);
  74650. }
  74651. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74652. // To handle the case of degenerated triangle
  74653. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74654. if (polygon.plane)
  74655. polygons.push(polygon);
  74656. }
  74657. }
  74658. var csg = CSG.FromPolygons(polygons);
  74659. csg.matrix = matrix;
  74660. csg.position = meshPosition;
  74661. csg.rotation = meshRotation;
  74662. csg.scaling = meshScaling;
  74663. csg.rotationQuaternion = meshRotationQuaternion;
  74664. currentCSGMeshId++;
  74665. return csg;
  74666. };
  74667. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74668. CSG.FromPolygons = function (polygons) {
  74669. var csg = new CSG();
  74670. csg.polygons = polygons;
  74671. return csg;
  74672. };
  74673. CSG.prototype.clone = function () {
  74674. var csg = new CSG();
  74675. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74676. csg.copyTransformAttributes(this);
  74677. return csg;
  74678. };
  74679. CSG.prototype.union = function (csg) {
  74680. var a = new Node(this.clone().polygons);
  74681. var b = new Node(csg.clone().polygons);
  74682. a.clipTo(b);
  74683. b.clipTo(a);
  74684. b.invert();
  74685. b.clipTo(a);
  74686. b.invert();
  74687. a.build(b.allPolygons());
  74688. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74689. };
  74690. CSG.prototype.unionInPlace = function (csg) {
  74691. var a = new Node(this.polygons);
  74692. var b = new Node(csg.polygons);
  74693. a.clipTo(b);
  74694. b.clipTo(a);
  74695. b.invert();
  74696. b.clipTo(a);
  74697. b.invert();
  74698. a.build(b.allPolygons());
  74699. this.polygons = a.allPolygons();
  74700. };
  74701. CSG.prototype.subtract = function (csg) {
  74702. var a = new Node(this.clone().polygons);
  74703. var b = new Node(csg.clone().polygons);
  74704. a.invert();
  74705. a.clipTo(b);
  74706. b.clipTo(a);
  74707. b.invert();
  74708. b.clipTo(a);
  74709. b.invert();
  74710. a.build(b.allPolygons());
  74711. a.invert();
  74712. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74713. };
  74714. CSG.prototype.subtractInPlace = function (csg) {
  74715. var a = new Node(this.polygons);
  74716. var b = new Node(csg.polygons);
  74717. a.invert();
  74718. a.clipTo(b);
  74719. b.clipTo(a);
  74720. b.invert();
  74721. b.clipTo(a);
  74722. b.invert();
  74723. a.build(b.allPolygons());
  74724. a.invert();
  74725. this.polygons = a.allPolygons();
  74726. };
  74727. CSG.prototype.intersect = function (csg) {
  74728. var a = new Node(this.clone().polygons);
  74729. var b = new Node(csg.clone().polygons);
  74730. a.invert();
  74731. b.clipTo(a);
  74732. b.invert();
  74733. a.clipTo(b);
  74734. b.clipTo(a);
  74735. a.build(b.allPolygons());
  74736. a.invert();
  74737. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74738. };
  74739. CSG.prototype.intersectInPlace = function (csg) {
  74740. var a = new Node(this.polygons);
  74741. var b = new Node(csg.polygons);
  74742. a.invert();
  74743. b.clipTo(a);
  74744. b.invert();
  74745. a.clipTo(b);
  74746. b.clipTo(a);
  74747. a.build(b.allPolygons());
  74748. a.invert();
  74749. this.polygons = a.allPolygons();
  74750. };
  74751. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74752. // not modified.
  74753. CSG.prototype.inverse = function () {
  74754. var csg = this.clone();
  74755. csg.inverseInPlace();
  74756. return csg;
  74757. };
  74758. CSG.prototype.inverseInPlace = function () {
  74759. this.polygons.map(function (p) { p.flip(); });
  74760. };
  74761. // This is used to keep meshes transformations so they can be restored
  74762. // when we build back a Babylon Mesh
  74763. // NB : All CSG operations are performed in world coordinates
  74764. CSG.prototype.copyTransformAttributes = function (csg) {
  74765. this.matrix = csg.matrix;
  74766. this.position = csg.position;
  74767. this.rotation = csg.rotation;
  74768. this.scaling = csg.scaling;
  74769. this.rotationQuaternion = csg.rotationQuaternion;
  74770. return this;
  74771. };
  74772. // Build Raw mesh from CSG
  74773. // Coordinates here are in world space
  74774. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74775. var matrix = this.matrix.clone();
  74776. matrix.invert();
  74777. 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;
  74778. if (keepSubMeshes) {
  74779. // Sort Polygons, since subMeshes are indices range
  74780. polygons.sort(function (a, b) {
  74781. if (a.shared.meshId === b.shared.meshId) {
  74782. return a.shared.subMeshId - b.shared.subMeshId;
  74783. }
  74784. else {
  74785. return a.shared.meshId - b.shared.meshId;
  74786. }
  74787. });
  74788. }
  74789. for (var i = 0, il = polygons.length; i < il; i++) {
  74790. polygon = polygons[i];
  74791. // Building SubMeshes
  74792. if (!subMesh_dict[polygon.shared.meshId]) {
  74793. subMesh_dict[polygon.shared.meshId] = {};
  74794. }
  74795. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74796. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74797. indexStart: +Infinity,
  74798. indexEnd: -Infinity,
  74799. materialIndex: polygon.shared.materialIndex
  74800. };
  74801. }
  74802. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74803. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74804. polygonIndices[0] = 0;
  74805. polygonIndices[1] = j - 1;
  74806. polygonIndices[2] = j;
  74807. for (var k = 0; k < 3; k++) {
  74808. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74809. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74810. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74811. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74812. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74813. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74814. // Check if 2 points can be merged
  74815. if (!(typeof vertex_idx !== 'undefined' &&
  74816. normals[vertex_idx * 3] === localNormal.x &&
  74817. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74818. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74819. uvs[vertex_idx * 2] === uv.x &&
  74820. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74821. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74822. uvs.push(uv.x, uv.y);
  74823. normals.push(normal.x, normal.y, normal.z);
  74824. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74825. }
  74826. indices.push(vertex_idx);
  74827. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74828. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74829. currentIndex++;
  74830. }
  74831. }
  74832. }
  74833. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74834. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74835. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74836. mesh.setIndices(indices, null);
  74837. if (keepSubMeshes) {
  74838. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74839. var materialIndexOffset = 0, materialMaxIndex;
  74840. mesh.subMeshes = new Array();
  74841. for (var m in subMesh_dict) {
  74842. materialMaxIndex = -1;
  74843. for (var sm in subMesh_dict[m]) {
  74844. subMesh_obj = subMesh_dict[m][sm];
  74845. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74846. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74847. }
  74848. materialIndexOffset += ++materialMaxIndex;
  74849. }
  74850. }
  74851. return mesh;
  74852. };
  74853. // Build Mesh from CSG taking material and transforms into account
  74854. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74855. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74856. mesh.material = material;
  74857. mesh.position.copyFrom(this.position);
  74858. mesh.rotation.copyFrom(this.rotation);
  74859. if (this.rotationQuaternion) {
  74860. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74861. }
  74862. mesh.scaling.copyFrom(this.scaling);
  74863. mesh.computeWorldMatrix(true);
  74864. return mesh;
  74865. };
  74866. return CSG;
  74867. }());
  74868. BABYLON.CSG = CSG;
  74869. })(BABYLON || (BABYLON = {}));
  74870. //# sourceMappingURL=babylon.csg.js.map
  74871. var BABYLON;
  74872. (function (BABYLON) {
  74873. var LensFlare = /** @class */ (function () {
  74874. function LensFlare(size, position, color, imgUrl, system) {
  74875. this.size = size;
  74876. this.position = position;
  74877. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74878. this.color = color || new BABYLON.Color3(1, 1, 1);
  74879. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74880. this._system = system;
  74881. system.lensFlares.push(this);
  74882. }
  74883. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74884. return new LensFlare(size, position, color, imgUrl, system);
  74885. };
  74886. LensFlare.prototype.dispose = function () {
  74887. if (this.texture) {
  74888. this.texture.dispose();
  74889. }
  74890. // Remove from scene
  74891. var index = this._system.lensFlares.indexOf(this);
  74892. this._system.lensFlares.splice(index, 1);
  74893. };
  74894. ;
  74895. return LensFlare;
  74896. }());
  74897. BABYLON.LensFlare = LensFlare;
  74898. })(BABYLON || (BABYLON = {}));
  74899. //# sourceMappingURL=babylon.lensFlare.js.map
  74900. var BABYLON;
  74901. (function (BABYLON) {
  74902. var LensFlareSystem = /** @class */ (function () {
  74903. function LensFlareSystem(name, emitter, scene) {
  74904. this.name = name;
  74905. this.lensFlares = new Array();
  74906. this.borderLimit = 300;
  74907. this.viewportBorder = 0;
  74908. this.layerMask = 0x0FFFFFFF;
  74909. this._vertexBuffers = {};
  74910. this._isEnabled = true;
  74911. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74912. this._emitter = emitter;
  74913. this.id = name;
  74914. scene.lensFlareSystems.push(this);
  74915. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74916. var engine = scene.getEngine();
  74917. // VBO
  74918. var vertices = [];
  74919. vertices.push(1, 1);
  74920. vertices.push(-1, 1);
  74921. vertices.push(-1, -1);
  74922. vertices.push(1, -1);
  74923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74924. // Indices
  74925. var indices = [];
  74926. indices.push(0);
  74927. indices.push(1);
  74928. indices.push(2);
  74929. indices.push(0);
  74930. indices.push(2);
  74931. indices.push(3);
  74932. this._indexBuffer = engine.createIndexBuffer(indices);
  74933. // Effects
  74934. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74935. }
  74936. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74937. get: function () {
  74938. return this._isEnabled;
  74939. },
  74940. set: function (value) {
  74941. this._isEnabled = value;
  74942. },
  74943. enumerable: true,
  74944. configurable: true
  74945. });
  74946. LensFlareSystem.prototype.getScene = function () {
  74947. return this._scene;
  74948. };
  74949. LensFlareSystem.prototype.getEmitter = function () {
  74950. return this._emitter;
  74951. };
  74952. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74953. this._emitter = newEmitter;
  74954. };
  74955. LensFlareSystem.prototype.getEmitterPosition = function () {
  74956. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74957. };
  74958. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74959. var position = this.getEmitterPosition();
  74960. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74961. this._positionX = position.x;
  74962. this._positionY = position.y;
  74963. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74964. if (this.viewportBorder > 0) {
  74965. globalViewport.x -= this.viewportBorder;
  74966. globalViewport.y -= this.viewportBorder;
  74967. globalViewport.width += this.viewportBorder * 2;
  74968. globalViewport.height += this.viewportBorder * 2;
  74969. position.x += this.viewportBorder;
  74970. position.y += this.viewportBorder;
  74971. this._positionX += this.viewportBorder;
  74972. this._positionY += this.viewportBorder;
  74973. }
  74974. if (position.z > 0) {
  74975. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74976. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74977. return true;
  74978. }
  74979. return true;
  74980. }
  74981. return false;
  74982. };
  74983. LensFlareSystem.prototype._isVisible = function () {
  74984. if (!this._isEnabled || !this._scene.activeCamera) {
  74985. return false;
  74986. }
  74987. var emitterPosition = this.getEmitterPosition();
  74988. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74989. var distance = direction.length();
  74990. direction.normalize();
  74991. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74992. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74993. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74994. };
  74995. LensFlareSystem.prototype.render = function () {
  74996. if (!this._effect.isReady() || !this._scene.activeCamera)
  74997. return false;
  74998. var engine = this._scene.getEngine();
  74999. var viewport = this._scene.activeCamera.viewport;
  75000. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75001. // Position
  75002. if (!this.computeEffectivePosition(globalViewport)) {
  75003. return false;
  75004. }
  75005. // Visibility
  75006. if (!this._isVisible()) {
  75007. return false;
  75008. }
  75009. // Intensity
  75010. var awayX;
  75011. var awayY;
  75012. if (this._positionX < this.borderLimit + globalViewport.x) {
  75013. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75014. }
  75015. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75016. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75017. }
  75018. else {
  75019. awayX = 0;
  75020. }
  75021. if (this._positionY < this.borderLimit + globalViewport.y) {
  75022. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75023. }
  75024. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75025. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75026. }
  75027. else {
  75028. awayY = 0;
  75029. }
  75030. var away = (awayX > awayY) ? awayX : awayY;
  75031. away -= this.viewportBorder;
  75032. if (away > this.borderLimit) {
  75033. away = this.borderLimit;
  75034. }
  75035. var intensity = 1.0 - (away / this.borderLimit);
  75036. if (intensity < 0) {
  75037. return false;
  75038. }
  75039. if (intensity > 1.0) {
  75040. intensity = 1.0;
  75041. }
  75042. if (this.viewportBorder > 0) {
  75043. globalViewport.x += this.viewportBorder;
  75044. globalViewport.y += this.viewportBorder;
  75045. globalViewport.width -= this.viewportBorder * 2;
  75046. globalViewport.height -= this.viewportBorder * 2;
  75047. this._positionX -= this.viewportBorder;
  75048. this._positionY -= this.viewportBorder;
  75049. }
  75050. // Position
  75051. var centerX = globalViewport.x + globalViewport.width / 2;
  75052. var centerY = globalViewport.y + globalViewport.height / 2;
  75053. var distX = centerX - this._positionX;
  75054. var distY = centerY - this._positionY;
  75055. // Effects
  75056. engine.enableEffect(this._effect);
  75057. engine.setState(false);
  75058. engine.setDepthBuffer(false);
  75059. // VBOs
  75060. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75061. // Flares
  75062. for (var index = 0; index < this.lensFlares.length; index++) {
  75063. var flare = this.lensFlares[index];
  75064. engine.setAlphaMode(flare.alphaMode);
  75065. var x = centerX - (distX * flare.position);
  75066. var y = centerY - (distY * flare.position);
  75067. var cw = flare.size;
  75068. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75069. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75070. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75071. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75072. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75073. // Texture
  75074. this._effect.setTexture("textureSampler", flare.texture);
  75075. // Color
  75076. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75077. // Draw order
  75078. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75079. }
  75080. engine.setDepthBuffer(true);
  75081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75082. return true;
  75083. };
  75084. LensFlareSystem.prototype.dispose = function () {
  75085. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75086. if (vertexBuffer) {
  75087. vertexBuffer.dispose();
  75088. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75089. }
  75090. if (this._indexBuffer) {
  75091. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75092. this._indexBuffer = null;
  75093. }
  75094. while (this.lensFlares.length) {
  75095. this.lensFlares[0].dispose();
  75096. }
  75097. // Remove from scene
  75098. var index = this._scene.lensFlareSystems.indexOf(this);
  75099. this._scene.lensFlareSystems.splice(index, 1);
  75100. };
  75101. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75102. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75103. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75104. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75105. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75106. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75107. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75108. var parsedFlare = parsedLensFlareSystem.flares[index];
  75109. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75110. }
  75111. return lensFlareSystem;
  75112. };
  75113. LensFlareSystem.prototype.serialize = function () {
  75114. var serializationObject = {};
  75115. serializationObject.id = this.id;
  75116. serializationObject.name = this.name;
  75117. serializationObject.emitterId = this.getEmitter().id;
  75118. serializationObject.borderLimit = this.borderLimit;
  75119. serializationObject.flares = [];
  75120. for (var index = 0; index < this.lensFlares.length; index++) {
  75121. var flare = this.lensFlares[index];
  75122. serializationObject.flares.push({
  75123. size: flare.size,
  75124. position: flare.position,
  75125. color: flare.color.asArray(),
  75126. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75127. });
  75128. }
  75129. return serializationObject;
  75130. };
  75131. return LensFlareSystem;
  75132. }());
  75133. BABYLON.LensFlareSystem = LensFlareSystem;
  75134. })(BABYLON || (BABYLON = {}));
  75135. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75136. var BABYLON;
  75137. (function (BABYLON) {
  75138. /**
  75139. * This is a holder class for the physics joint created by the physics plugin.
  75140. * It holds a set of functions to control the underlying joint.
  75141. */
  75142. var PhysicsJoint = /** @class */ (function () {
  75143. function PhysicsJoint(type, jointData) {
  75144. this.type = type;
  75145. this.jointData = jointData;
  75146. jointData.nativeParams = jointData.nativeParams || {};
  75147. }
  75148. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75149. get: function () {
  75150. return this._physicsJoint;
  75151. },
  75152. set: function (newJoint) {
  75153. if (this._physicsJoint) {
  75154. //remove from the wolrd
  75155. }
  75156. this._physicsJoint = newJoint;
  75157. },
  75158. enumerable: true,
  75159. configurable: true
  75160. });
  75161. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75162. set: function (physicsPlugin) {
  75163. this._physicsPlugin = physicsPlugin;
  75164. },
  75165. enumerable: true,
  75166. configurable: true
  75167. });
  75168. /**
  75169. * Execute a function that is physics-plugin specific.
  75170. * @param {Function} func the function that will be executed.
  75171. * It accepts two parameters: the physics world and the physics joint.
  75172. */
  75173. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75174. func(this._physicsPlugin.world, this._physicsJoint);
  75175. };
  75176. //TODO check if the native joints are the same
  75177. //Joint Types
  75178. PhysicsJoint.DistanceJoint = 0;
  75179. PhysicsJoint.HingeJoint = 1;
  75180. PhysicsJoint.BallAndSocketJoint = 2;
  75181. PhysicsJoint.WheelJoint = 3;
  75182. PhysicsJoint.SliderJoint = 4;
  75183. //OIMO
  75184. PhysicsJoint.PrismaticJoint = 5;
  75185. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75186. PhysicsJoint.UniversalJoint = 6;
  75187. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75188. //Cannon
  75189. //Similar to a Ball-Joint. Different in params
  75190. PhysicsJoint.PointToPointJoint = 8;
  75191. //Cannon only at the moment
  75192. PhysicsJoint.SpringJoint = 9;
  75193. PhysicsJoint.LockJoint = 10;
  75194. return PhysicsJoint;
  75195. }());
  75196. BABYLON.PhysicsJoint = PhysicsJoint;
  75197. /**
  75198. * A class representing a physics distance joint.
  75199. */
  75200. var DistanceJoint = /** @class */ (function (_super) {
  75201. __extends(DistanceJoint, _super);
  75202. function DistanceJoint(jointData) {
  75203. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75204. }
  75205. /**
  75206. * Update the predefined distance.
  75207. */
  75208. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75209. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75210. };
  75211. return DistanceJoint;
  75212. }(PhysicsJoint));
  75213. BABYLON.DistanceJoint = DistanceJoint;
  75214. var MotorEnabledJoint = /** @class */ (function (_super) {
  75215. __extends(MotorEnabledJoint, _super);
  75216. function MotorEnabledJoint(type, jointData) {
  75217. return _super.call(this, type, jointData) || this;
  75218. }
  75219. /**
  75220. * Set the motor values.
  75221. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75222. * @param {number} force the force to apply
  75223. * @param {number} maxForce max force for this motor.
  75224. */
  75225. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75226. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75227. };
  75228. /**
  75229. * Set the motor's limits.
  75230. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75231. */
  75232. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75233. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75234. };
  75235. return MotorEnabledJoint;
  75236. }(PhysicsJoint));
  75237. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75238. /**
  75239. * This class represents a single hinge physics joint
  75240. */
  75241. var HingeJoint = /** @class */ (function (_super) {
  75242. __extends(HingeJoint, _super);
  75243. function HingeJoint(jointData) {
  75244. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75245. }
  75246. /**
  75247. * Set the motor values.
  75248. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75249. * @param {number} force the force to apply
  75250. * @param {number} maxForce max force for this motor.
  75251. */
  75252. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75253. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75254. };
  75255. /**
  75256. * Set the motor's limits.
  75257. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75258. */
  75259. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75260. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75261. };
  75262. return HingeJoint;
  75263. }(MotorEnabledJoint));
  75264. BABYLON.HingeJoint = HingeJoint;
  75265. /**
  75266. * This class represents a dual hinge physics joint (same as wheel joint)
  75267. */
  75268. var Hinge2Joint = /** @class */ (function (_super) {
  75269. __extends(Hinge2Joint, _super);
  75270. function Hinge2Joint(jointData) {
  75271. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75272. }
  75273. /**
  75274. * Set the motor values.
  75275. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75276. * @param {number} force the force to apply
  75277. * @param {number} maxForce max force for this motor.
  75278. * @param {motorIndex} the motor's index, 0 or 1.
  75279. */
  75280. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75281. if (motorIndex === void 0) { motorIndex = 0; }
  75282. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75283. };
  75284. /**
  75285. * Set the motor limits.
  75286. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75287. * @param {number} upperLimit the upper limit
  75288. * @param {number} lowerLimit lower limit
  75289. * @param {motorIndex} the motor's index, 0 or 1.
  75290. */
  75291. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75292. if (motorIndex === void 0) { motorIndex = 0; }
  75293. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75294. };
  75295. return Hinge2Joint;
  75296. }(MotorEnabledJoint));
  75297. BABYLON.Hinge2Joint = Hinge2Joint;
  75298. })(BABYLON || (BABYLON = {}));
  75299. //# sourceMappingURL=babylon.physicsJoint.js.map
  75300. var BABYLON;
  75301. (function (BABYLON) {
  75302. var PhysicsImpostor = /** @class */ (function () {
  75303. function PhysicsImpostor(object, type, _options, _scene) {
  75304. if (_options === void 0) { _options = { mass: 0 }; }
  75305. var _this = this;
  75306. this.object = object;
  75307. this.type = type;
  75308. this._options = _options;
  75309. this._scene = _scene;
  75310. this._bodyUpdateRequired = false;
  75311. this._onBeforePhysicsStepCallbacks = new Array();
  75312. this._onAfterPhysicsStepCallbacks = new Array();
  75313. this._onPhysicsCollideCallbacks = [];
  75314. this._deltaPosition = BABYLON.Vector3.Zero();
  75315. this._isDisposed = false;
  75316. //temp variables for parent rotation calculations
  75317. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75318. this._tmpQuat = new BABYLON.Quaternion();
  75319. this._tmpQuat2 = new BABYLON.Quaternion();
  75320. /**
  75321. * this function is executed by the physics engine.
  75322. */
  75323. this.beforeStep = function () {
  75324. if (!_this._physicsEngine) {
  75325. return;
  75326. }
  75327. _this.object.translate(_this._deltaPosition, -1);
  75328. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75329. _this.object.computeWorldMatrix(false);
  75330. if (_this.object.parent && _this.object.rotationQuaternion) {
  75331. _this.getParentsRotation();
  75332. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75333. }
  75334. else {
  75335. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75336. }
  75337. if (!_this._options.disableBidirectionalTransformation) {
  75338. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75339. }
  75340. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75341. func(_this);
  75342. });
  75343. };
  75344. /**
  75345. * this function is executed by the physics engine.
  75346. */
  75347. this.afterStep = function () {
  75348. if (!_this._physicsEngine) {
  75349. return;
  75350. }
  75351. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75352. func(_this);
  75353. });
  75354. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75355. // object has now its world rotation. needs to be converted to local.
  75356. if (_this.object.parent && _this.object.rotationQuaternion) {
  75357. _this.getParentsRotation();
  75358. _this._tmpQuat.conjugateInPlace();
  75359. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75360. }
  75361. // take the position set and make it the absolute position of this object.
  75362. _this.object.setAbsolutePosition(_this.object.position);
  75363. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75364. _this.object.translate(_this._deltaPosition, 1);
  75365. };
  75366. /**
  75367. * Legacy collision detection event support
  75368. */
  75369. this.onCollideEvent = null;
  75370. //event and body object due to cannon's event-based architecture.
  75371. this.onCollide = function (e) {
  75372. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75373. return;
  75374. }
  75375. if (!_this._physicsEngine) {
  75376. return;
  75377. }
  75378. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75379. if (otherImpostor) {
  75380. // Legacy collision detection event support
  75381. if (_this.onCollideEvent) {
  75382. _this.onCollideEvent(_this, otherImpostor);
  75383. }
  75384. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75385. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75386. }).forEach(function (obj) {
  75387. obj.callback(_this, otherImpostor);
  75388. });
  75389. }
  75390. };
  75391. //sanity check!
  75392. if (!this.object) {
  75393. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75394. return;
  75395. }
  75396. //legacy support for old syntax.
  75397. if (!this._scene && object.getScene) {
  75398. this._scene = object.getScene();
  75399. }
  75400. if (!this._scene) {
  75401. return;
  75402. }
  75403. this._physicsEngine = this._scene.getPhysicsEngine();
  75404. if (!this._physicsEngine) {
  75405. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75406. }
  75407. else {
  75408. //set the object's quaternion, if not set
  75409. if (!this.object.rotationQuaternion) {
  75410. if (this.object.rotation) {
  75411. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75412. }
  75413. else {
  75414. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75415. }
  75416. }
  75417. //default options params
  75418. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75419. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75420. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75421. this._joints = [];
  75422. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75423. if (!this.object.parent || this._options.ignoreParent) {
  75424. this._init();
  75425. }
  75426. else if (this.object.parent.physicsImpostor) {
  75427. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75428. }
  75429. }
  75430. }
  75431. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75432. get: function () {
  75433. return this._isDisposed;
  75434. },
  75435. enumerable: true,
  75436. configurable: true
  75437. });
  75438. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75439. get: function () {
  75440. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75441. },
  75442. set: function (value) {
  75443. this.setMass(value);
  75444. },
  75445. enumerable: true,
  75446. configurable: true
  75447. });
  75448. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75449. get: function () {
  75450. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75451. },
  75452. set: function (value) {
  75453. if (!this._physicsEngine) {
  75454. return;
  75455. }
  75456. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75457. },
  75458. enumerable: true,
  75459. configurable: true
  75460. });
  75461. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75462. get: function () {
  75463. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75464. },
  75465. set: function (value) {
  75466. if (!this._physicsEngine) {
  75467. return;
  75468. }
  75469. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75470. },
  75471. enumerable: true,
  75472. configurable: true
  75473. });
  75474. /**
  75475. * This function will completly initialize this impostor.
  75476. * It will create a new body - but only if this mesh has no parent.
  75477. * If it has, this impostor will not be used other than to define the impostor
  75478. * of the child mesh.
  75479. */
  75480. PhysicsImpostor.prototype._init = function () {
  75481. if (!this._physicsEngine) {
  75482. return;
  75483. }
  75484. this._physicsEngine.removeImpostor(this);
  75485. this.physicsBody = null;
  75486. this._parent = this._parent || this._getPhysicsParent();
  75487. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75488. this._physicsEngine.addImpostor(this);
  75489. }
  75490. };
  75491. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75492. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75493. var parentMesh = this.object.parent;
  75494. return parentMesh.physicsImpostor;
  75495. }
  75496. return null;
  75497. };
  75498. /**
  75499. * Should a new body be generated.
  75500. */
  75501. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75502. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75503. };
  75504. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75505. this.forceUpdate();
  75506. };
  75507. /**
  75508. * Force a regeneration of this or the parent's impostor's body.
  75509. * Use under cautious - This will remove all joints already implemented.
  75510. */
  75511. PhysicsImpostor.prototype.forceUpdate = function () {
  75512. this._init();
  75513. if (this.parent && !this._options.ignoreParent) {
  75514. this.parent.forceUpdate();
  75515. }
  75516. };
  75517. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75518. /*public get mesh(): AbstractMesh {
  75519. return this._mesh;
  75520. }*/
  75521. /**
  75522. * Gets the body that holds this impostor. Either its own, or its parent.
  75523. */
  75524. get: function () {
  75525. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75526. },
  75527. /**
  75528. * Set the physics body. Used mainly by the physics engine/plugin
  75529. */
  75530. set: function (physicsBody) {
  75531. if (this._physicsBody && this._physicsEngine) {
  75532. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75533. }
  75534. this._physicsBody = physicsBody;
  75535. this.resetUpdateFlags();
  75536. },
  75537. enumerable: true,
  75538. configurable: true
  75539. });
  75540. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75541. get: function () {
  75542. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75543. },
  75544. set: function (value) {
  75545. this._parent = value;
  75546. },
  75547. enumerable: true,
  75548. configurable: true
  75549. });
  75550. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75551. this._bodyUpdateRequired = false;
  75552. };
  75553. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75554. if (this.object.getBoundingInfo) {
  75555. var q = this.object.rotationQuaternion;
  75556. //reset rotation
  75557. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75558. //calculate the world matrix with no rotation
  75559. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75560. var boundingInfo = this.object.getBoundingInfo();
  75561. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75562. //bring back the rotation
  75563. this.object.rotationQuaternion = q;
  75564. //calculate the world matrix with the new rotation
  75565. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75566. return size;
  75567. }
  75568. else {
  75569. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75570. }
  75571. };
  75572. PhysicsImpostor.prototype.getObjectCenter = function () {
  75573. if (this.object.getBoundingInfo) {
  75574. var boundingInfo = this.object.getBoundingInfo();
  75575. return boundingInfo.boundingBox.centerWorld;
  75576. }
  75577. else {
  75578. return this.object.position;
  75579. }
  75580. };
  75581. /**
  75582. * Get a specific parametes from the options parameter.
  75583. */
  75584. PhysicsImpostor.prototype.getParam = function (paramName) {
  75585. return this._options[paramName];
  75586. };
  75587. /**
  75588. * Sets a specific parameter in the options given to the physics plugin
  75589. */
  75590. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75591. this._options[paramName] = value;
  75592. this._bodyUpdateRequired = true;
  75593. };
  75594. /**
  75595. * Specifically change the body's mass option. Won't recreate the physics body object
  75596. */
  75597. PhysicsImpostor.prototype.setMass = function (mass) {
  75598. if (this.getParam("mass") !== mass) {
  75599. this.setParam("mass", mass);
  75600. }
  75601. if (this._physicsEngine) {
  75602. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75603. }
  75604. };
  75605. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75606. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75607. };
  75608. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75609. if (this._physicsEngine) {
  75610. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75611. }
  75612. };
  75613. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75614. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75615. };
  75616. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75617. if (this._physicsEngine) {
  75618. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75619. }
  75620. };
  75621. /**
  75622. * Execute a function with the physics plugin native code.
  75623. * Provide a function the will have two variables - the world object and the physics body object.
  75624. */
  75625. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75626. if (this._physicsEngine) {
  75627. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75628. }
  75629. };
  75630. /**
  75631. * Register a function that will be executed before the physics world is stepping forward.
  75632. */
  75633. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75634. this._onBeforePhysicsStepCallbacks.push(func);
  75635. };
  75636. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75637. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75638. if (index > -1) {
  75639. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75640. }
  75641. else {
  75642. BABYLON.Tools.Warn("Function to remove was not found");
  75643. }
  75644. };
  75645. /**
  75646. * Register a function that will be executed after the physics step
  75647. */
  75648. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75649. this._onAfterPhysicsStepCallbacks.push(func);
  75650. };
  75651. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75652. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75653. if (index > -1) {
  75654. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75655. }
  75656. else {
  75657. BABYLON.Tools.Warn("Function to remove was not found");
  75658. }
  75659. };
  75660. /**
  75661. * register a function that will be executed when this impostor collides against a different body.
  75662. */
  75663. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75664. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75665. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75666. };
  75667. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75668. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75669. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75670. if (index > -1) {
  75671. this._onPhysicsCollideCallbacks.splice(index, 1);
  75672. }
  75673. else {
  75674. BABYLON.Tools.Warn("Function to remove was not found");
  75675. }
  75676. };
  75677. PhysicsImpostor.prototype.getParentsRotation = function () {
  75678. var parent = this.object.parent;
  75679. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75680. while (parent) {
  75681. if (parent.rotationQuaternion) {
  75682. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75683. }
  75684. else {
  75685. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75686. }
  75687. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75688. parent = parent.parent;
  75689. }
  75690. return this._tmpQuat;
  75691. };
  75692. /**
  75693. * Apply a force
  75694. */
  75695. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75696. if (this._physicsEngine) {
  75697. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75698. }
  75699. return this;
  75700. };
  75701. /**
  75702. * Apply an impulse
  75703. */
  75704. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75705. if (this._physicsEngine) {
  75706. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75707. }
  75708. return this;
  75709. };
  75710. /**
  75711. * A help function to create a joint.
  75712. */
  75713. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75714. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75715. this.addJoint(otherImpostor, joint);
  75716. return this;
  75717. };
  75718. /**
  75719. * Add a joint to this impostor with a different impostor.
  75720. */
  75721. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75722. this._joints.push({
  75723. otherImpostor: otherImpostor,
  75724. joint: joint
  75725. });
  75726. if (this._physicsEngine) {
  75727. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75728. }
  75729. return this;
  75730. };
  75731. /**
  75732. * Will keep this body still, in a sleep mode.
  75733. */
  75734. PhysicsImpostor.prototype.sleep = function () {
  75735. if (this._physicsEngine) {
  75736. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75737. }
  75738. return this;
  75739. };
  75740. /**
  75741. * Wake the body up.
  75742. */
  75743. PhysicsImpostor.prototype.wakeUp = function () {
  75744. if (this._physicsEngine) {
  75745. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75746. }
  75747. return this;
  75748. };
  75749. PhysicsImpostor.prototype.clone = function (newObject) {
  75750. if (!newObject)
  75751. return null;
  75752. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75753. };
  75754. PhysicsImpostor.prototype.dispose = function () {
  75755. var _this = this;
  75756. //no dispose if no physics engine is available.
  75757. if (!this._physicsEngine) {
  75758. return;
  75759. }
  75760. this._joints.forEach(function (j) {
  75761. if (_this._physicsEngine) {
  75762. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75763. }
  75764. });
  75765. //dispose the physics body
  75766. this._physicsEngine.removeImpostor(this);
  75767. if (this.parent) {
  75768. this.parent.forceUpdate();
  75769. }
  75770. else {
  75771. /*this._object.getChildMeshes().forEach(function(mesh) {
  75772. if (mesh.physicsImpostor) {
  75773. if (disposeChildren) {
  75774. mesh.physicsImpostor.dispose();
  75775. mesh.physicsImpostor = null;
  75776. }
  75777. }
  75778. })*/
  75779. }
  75780. this._isDisposed = true;
  75781. };
  75782. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75783. this._deltaPosition.copyFrom(position);
  75784. };
  75785. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75786. if (!this._deltaRotation) {
  75787. this._deltaRotation = new BABYLON.Quaternion();
  75788. }
  75789. this._deltaRotation.copyFrom(rotation);
  75790. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75791. };
  75792. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75793. if (this._physicsEngine) {
  75794. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75795. }
  75796. return this;
  75797. };
  75798. PhysicsImpostor.prototype.getRadius = function () {
  75799. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75800. };
  75801. /**
  75802. * Sync a bone with this impostor
  75803. * @param bone The bone to sync to the impostor.
  75804. * @param boneMesh The mesh that the bone is influencing.
  75805. * @param jointPivot The pivot of the joint / bone in local space.
  75806. * @param distToJoint Optional distance from the impostor to the joint.
  75807. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75808. */
  75809. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75810. var tempVec = PhysicsImpostor._tmpVecs[0];
  75811. var mesh = this.object;
  75812. if (mesh.rotationQuaternion) {
  75813. if (adjustRotation) {
  75814. var tempQuat = PhysicsImpostor._tmpQuat;
  75815. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75816. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75817. }
  75818. else {
  75819. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75820. }
  75821. }
  75822. tempVec.x = 0;
  75823. tempVec.y = 0;
  75824. tempVec.z = 0;
  75825. if (jointPivot) {
  75826. tempVec.x = jointPivot.x;
  75827. tempVec.y = jointPivot.y;
  75828. tempVec.z = jointPivot.z;
  75829. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75830. if (distToJoint === undefined || distToJoint === null) {
  75831. distToJoint = jointPivot.length();
  75832. }
  75833. tempVec.x *= distToJoint;
  75834. tempVec.y *= distToJoint;
  75835. tempVec.z *= distToJoint;
  75836. }
  75837. if (bone.getParent()) {
  75838. tempVec.addInPlace(mesh.getAbsolutePosition());
  75839. bone.setAbsolutePosition(tempVec, boneMesh);
  75840. }
  75841. else {
  75842. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75843. boneMesh.position.x -= tempVec.x;
  75844. boneMesh.position.y -= tempVec.y;
  75845. boneMesh.position.z -= tempVec.z;
  75846. }
  75847. };
  75848. /**
  75849. * Sync impostor to a bone
  75850. * @param bone The bone that the impostor will be synced to.
  75851. * @param boneMesh The mesh that the bone is influencing.
  75852. * @param jointPivot The pivot of the joint / bone in local space.
  75853. * @param distToJoint Optional distance from the impostor to the joint.
  75854. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75855. * @param boneAxis Optional vector3 axis the bone is aligned with
  75856. */
  75857. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75858. var mesh = this.object;
  75859. if (mesh.rotationQuaternion) {
  75860. if (adjustRotation) {
  75861. var tempQuat = PhysicsImpostor._tmpQuat;
  75862. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75863. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75864. }
  75865. else {
  75866. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75867. }
  75868. }
  75869. var pos = PhysicsImpostor._tmpVecs[0];
  75870. var boneDir = PhysicsImpostor._tmpVecs[1];
  75871. if (!boneAxis) {
  75872. boneAxis = PhysicsImpostor._tmpVecs[2];
  75873. boneAxis.x = 0;
  75874. boneAxis.y = 1;
  75875. boneAxis.z = 0;
  75876. }
  75877. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75878. bone.getAbsolutePositionToRef(boneMesh, pos);
  75879. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75880. distToJoint = jointPivot.length();
  75881. }
  75882. if (distToJoint !== undefined && distToJoint !== null) {
  75883. pos.x += boneDir.x * distToJoint;
  75884. pos.y += boneDir.y * distToJoint;
  75885. pos.z += boneDir.z * distToJoint;
  75886. }
  75887. mesh.setAbsolutePosition(pos);
  75888. };
  75889. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75890. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75891. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75892. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75893. //Impostor types
  75894. PhysicsImpostor.NoImpostor = 0;
  75895. PhysicsImpostor.SphereImpostor = 1;
  75896. PhysicsImpostor.BoxImpostor = 2;
  75897. PhysicsImpostor.PlaneImpostor = 3;
  75898. PhysicsImpostor.MeshImpostor = 4;
  75899. PhysicsImpostor.CylinderImpostor = 7;
  75900. PhysicsImpostor.ParticleImpostor = 8;
  75901. PhysicsImpostor.HeightmapImpostor = 9;
  75902. return PhysicsImpostor;
  75903. }());
  75904. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75905. })(BABYLON || (BABYLON = {}));
  75906. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75907. var BABYLON;
  75908. (function (BABYLON) {
  75909. var PhysicsEngine = /** @class */ (function () {
  75910. function PhysicsEngine(gravity, _physicsPlugin) {
  75911. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75912. this._physicsPlugin = _physicsPlugin;
  75913. //new methods and parameters
  75914. this._impostors = [];
  75915. this._joints = [];
  75916. if (!this._physicsPlugin.isSupported()) {
  75917. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75918. + "Please make sure it is included.");
  75919. }
  75920. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75921. this.setGravity(gravity);
  75922. this.setTimeStep();
  75923. }
  75924. PhysicsEngine.prototype.setGravity = function (gravity) {
  75925. this.gravity = gravity;
  75926. this._physicsPlugin.setGravity(this.gravity);
  75927. };
  75928. /**
  75929. * Set the time step of the physics engine.
  75930. * default is 1/60.
  75931. * To slow it down, enter 1/600 for example.
  75932. * To speed it up, 1/30
  75933. * @param {number} newTimeStep the new timestep to apply to this world.
  75934. */
  75935. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75936. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75937. this._physicsPlugin.setTimeStep(newTimeStep);
  75938. };
  75939. /**
  75940. * Get the time step of the physics engine.
  75941. */
  75942. PhysicsEngine.prototype.getTimeStep = function () {
  75943. return this._physicsPlugin.getTimeStep();
  75944. };
  75945. PhysicsEngine.prototype.dispose = function () {
  75946. this._impostors.forEach(function (impostor) {
  75947. impostor.dispose();
  75948. });
  75949. this._physicsPlugin.dispose();
  75950. };
  75951. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75952. return this._physicsPlugin.name;
  75953. };
  75954. /**
  75955. * Adding a new impostor for the impostor tracking.
  75956. * This will be done by the impostor itself.
  75957. * @param {PhysicsImpostor} impostor the impostor to add
  75958. */
  75959. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75960. impostor.uniqueId = this._impostors.push(impostor);
  75961. //if no parent, generate the body
  75962. if (!impostor.parent) {
  75963. this._physicsPlugin.generatePhysicsBody(impostor);
  75964. }
  75965. };
  75966. /**
  75967. * Remove an impostor from the engine.
  75968. * This impostor and its mesh will not longer be updated by the physics engine.
  75969. * @param {PhysicsImpostor} impostor the impostor to remove
  75970. */
  75971. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75972. var index = this._impostors.indexOf(impostor);
  75973. if (index > -1) {
  75974. var removed = this._impostors.splice(index, 1);
  75975. //Is it needed?
  75976. if (removed.length) {
  75977. //this will also remove it from the world.
  75978. removed[0].physicsBody = null;
  75979. }
  75980. }
  75981. };
  75982. /**
  75983. * Add a joint to the physics engine
  75984. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75985. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75986. * @param {PhysicsJoint} the joint that will connect both impostors.
  75987. */
  75988. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75989. var impostorJoint = {
  75990. mainImpostor: mainImpostor,
  75991. connectedImpostor: connectedImpostor,
  75992. joint: joint
  75993. };
  75994. joint.physicsPlugin = this._physicsPlugin;
  75995. this._joints.push(impostorJoint);
  75996. this._physicsPlugin.generateJoint(impostorJoint);
  75997. };
  75998. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75999. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76000. return (impostorJoint.connectedImpostor === connectedImpostor
  76001. && impostorJoint.joint === joint
  76002. && impostorJoint.mainImpostor === mainImpostor);
  76003. });
  76004. if (matchingJoints.length) {
  76005. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76006. //TODO remove it from the list as well
  76007. }
  76008. };
  76009. /**
  76010. * Called by the scene. no need to call it.
  76011. */
  76012. PhysicsEngine.prototype._step = function (delta) {
  76013. var _this = this;
  76014. //check if any mesh has no body / requires an update
  76015. this._impostors.forEach(function (impostor) {
  76016. if (impostor.isBodyInitRequired()) {
  76017. _this._physicsPlugin.generatePhysicsBody(impostor);
  76018. }
  76019. });
  76020. if (delta > 0.1) {
  76021. delta = 0.1;
  76022. }
  76023. else if (delta <= 0) {
  76024. delta = 1.0 / 60.0;
  76025. }
  76026. this._physicsPlugin.executeStep(delta, this._impostors);
  76027. };
  76028. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76029. return this._physicsPlugin;
  76030. };
  76031. PhysicsEngine.prototype.getImpostors = function () {
  76032. return this._impostors;
  76033. };
  76034. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76035. for (var i = 0; i < this._impostors.length; ++i) {
  76036. if (this._impostors[i].object === object) {
  76037. return this._impostors[i];
  76038. }
  76039. }
  76040. return null;
  76041. };
  76042. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76043. for (var i = 0; i < this._impostors.length; ++i) {
  76044. if (this._impostors[i].physicsBody === body) {
  76045. return this._impostors[i];
  76046. }
  76047. }
  76048. return null;
  76049. };
  76050. // Statics
  76051. PhysicsEngine.Epsilon = 0.001;
  76052. return PhysicsEngine;
  76053. }());
  76054. BABYLON.PhysicsEngine = PhysicsEngine;
  76055. })(BABYLON || (BABYLON = {}));
  76056. //# sourceMappingURL=babylon.physicsEngine.js.map
  76057. var BABYLON;
  76058. (function (BABYLON) {
  76059. var PhysicsHelper = /** @class */ (function () {
  76060. function PhysicsHelper(scene) {
  76061. this._scene = scene;
  76062. this._physicsEngine = this._scene.getPhysicsEngine();
  76063. if (!this._physicsEngine) {
  76064. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76065. }
  76066. }
  76067. /**
  76068. * @param {Vector3} origin the origin of the explosion
  76069. * @param {number} radius the explosion radius
  76070. * @param {number} strength the explosion strength
  76071. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76072. */
  76073. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76074. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76075. if (!this._physicsEngine) {
  76076. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76077. return null;
  76078. }
  76079. var impostors = this._physicsEngine.getImpostors();
  76080. if (impostors.length === 0) {
  76081. return null;
  76082. }
  76083. var event = new PhysicsRadialExplosionEvent(this._scene);
  76084. impostors.forEach(function (impostor) {
  76085. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76086. if (!impostorForceAndContactPoint) {
  76087. return;
  76088. }
  76089. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76090. });
  76091. event.dispose(false);
  76092. return event;
  76093. };
  76094. /**
  76095. * @param {Vector3} origin the origin of the explosion
  76096. * @param {number} radius the explosion radius
  76097. * @param {number} strength the explosion strength
  76098. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76099. */
  76100. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76101. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76102. if (!this._physicsEngine) {
  76103. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76104. return null;
  76105. }
  76106. var impostors = this._physicsEngine.getImpostors();
  76107. if (impostors.length === 0) {
  76108. return null;
  76109. }
  76110. var event = new PhysicsRadialExplosionEvent(this._scene);
  76111. impostors.forEach(function (impostor) {
  76112. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76113. if (!impostorForceAndContactPoint) {
  76114. return;
  76115. }
  76116. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76117. });
  76118. event.dispose(false);
  76119. return event;
  76120. };
  76121. /**
  76122. * @param {Vector3} origin the origin of the explosion
  76123. * @param {number} radius the explosion radius
  76124. * @param {number} strength the explosion strength
  76125. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76126. */
  76127. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76128. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76129. if (!this._physicsEngine) {
  76130. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76131. return null;
  76132. }
  76133. var impostors = this._physicsEngine.getImpostors();
  76134. if (impostors.length === 0) {
  76135. return null;
  76136. }
  76137. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76138. event.dispose(false);
  76139. return event;
  76140. };
  76141. /**
  76142. * @param {Vector3} origin the origin of the updraft
  76143. * @param {number} radius the radius of the updraft
  76144. * @param {number} strength the strength of the updraft
  76145. * @param {number} height the height of the updraft
  76146. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76147. */
  76148. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76149. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76150. if (!this._physicsEngine) {
  76151. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76152. return null;
  76153. }
  76154. if (this._physicsEngine.getImpostors().length === 0) {
  76155. return null;
  76156. }
  76157. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76158. event.dispose(false);
  76159. return event;
  76160. };
  76161. /**
  76162. * @param {Vector3} origin the of the vortex
  76163. * @param {number} radius the radius of the vortex
  76164. * @param {number} strength the strength of the vortex
  76165. * @param {number} height the height of the vortex
  76166. */
  76167. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76168. if (!this._physicsEngine) {
  76169. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76170. return null;
  76171. }
  76172. if (this._physicsEngine.getImpostors().length === 0) {
  76173. return null;
  76174. }
  76175. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76176. event.dispose(false);
  76177. return event;
  76178. };
  76179. return PhysicsHelper;
  76180. }());
  76181. BABYLON.PhysicsHelper = PhysicsHelper;
  76182. /***** Radial explosion *****/
  76183. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76184. function PhysicsRadialExplosionEvent(scene) {
  76185. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76186. this._rays = [];
  76187. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76188. this._scene = scene;
  76189. }
  76190. /**
  76191. * Returns the data related to the radial explosion event (sphere & rays).
  76192. * @returns {PhysicsRadialExplosionEventData}
  76193. */
  76194. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76195. this._dataFetched = true;
  76196. return {
  76197. sphere: this._sphere,
  76198. rays: this._rays,
  76199. };
  76200. };
  76201. /**
  76202. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76203. * @param impostor
  76204. * @param {Vector3} origin the origin of the explosion
  76205. * @param {number} radius the explosion radius
  76206. * @param {number} strength the explosion strength
  76207. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76208. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76209. */
  76210. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76211. if (impostor.mass === 0) {
  76212. return null;
  76213. }
  76214. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76215. return null;
  76216. }
  76217. if (impostor.object.getClassName() !== 'Mesh') {
  76218. return null;
  76219. }
  76220. var impostorObject = impostor.object;
  76221. var impostorObjectCenter = impostor.getObjectCenter();
  76222. var direction = impostorObjectCenter.subtract(origin);
  76223. var ray = new BABYLON.Ray(origin, direction, radius);
  76224. this._rays.push(ray);
  76225. var hit = ray.intersectsMesh(impostorObject);
  76226. var contactPoint = hit.pickedPoint;
  76227. if (!contactPoint) {
  76228. return null;
  76229. }
  76230. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76231. if (distanceFromOrigin > radius) {
  76232. return null;
  76233. }
  76234. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76235. ? strength
  76236. : strength * (1 - (distanceFromOrigin / radius));
  76237. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76238. return { force: force, contactPoint: contactPoint };
  76239. };
  76240. /**
  76241. * Disposes the sphere.
  76242. * @param {bolean} force
  76243. */
  76244. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76245. var _this = this;
  76246. if (force === void 0) { force = true; }
  76247. if (force) {
  76248. this._sphere.dispose();
  76249. }
  76250. else {
  76251. setTimeout(function () {
  76252. if (!_this._dataFetched) {
  76253. _this._sphere.dispose();
  76254. }
  76255. }, 0);
  76256. }
  76257. };
  76258. /*** Helpers ***/
  76259. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76260. if (!this._sphere) {
  76261. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76262. this._sphere.isVisible = false;
  76263. }
  76264. };
  76265. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76266. var impostorObject = impostor.object;
  76267. this._prepareSphere();
  76268. this._sphere.position = origin;
  76269. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76270. this._sphere._updateBoundingInfo();
  76271. this._sphere.computeWorldMatrix(true);
  76272. return this._sphere.intersectsMesh(impostorObject, true);
  76273. };
  76274. return PhysicsRadialExplosionEvent;
  76275. }());
  76276. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76277. /***** Gravitational Field *****/
  76278. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76279. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76280. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76281. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76282. this._physicsHelper = physicsHelper;
  76283. this._scene = scene;
  76284. this._origin = origin;
  76285. this._radius = radius;
  76286. this._strength = strength;
  76287. this._falloff = falloff;
  76288. this._tickCallback = this._tick.bind(this);
  76289. }
  76290. /**
  76291. * Returns the data related to the gravitational field event (sphere).
  76292. * @returns {PhysicsGravitationalFieldEventData}
  76293. */
  76294. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76295. this._dataFetched = true;
  76296. return {
  76297. sphere: this._sphere,
  76298. };
  76299. };
  76300. /**
  76301. * Enables the gravitational field.
  76302. */
  76303. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76304. this._tickCallback.call(this);
  76305. this._scene.registerBeforeRender(this._tickCallback);
  76306. };
  76307. /**
  76308. * Disables the gravitational field.
  76309. */
  76310. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76311. this._scene.unregisterBeforeRender(this._tickCallback);
  76312. };
  76313. /**
  76314. * Disposes the sphere.
  76315. * @param {bolean} force
  76316. */
  76317. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76318. var _this = this;
  76319. if (force === void 0) { force = true; }
  76320. if (force) {
  76321. this._sphere.dispose();
  76322. }
  76323. else {
  76324. setTimeout(function () {
  76325. if (!_this._dataFetched) {
  76326. _this._sphere.dispose();
  76327. }
  76328. }, 0);
  76329. }
  76330. };
  76331. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76332. // Since the params won't change, we fetch the event only once
  76333. if (this._sphere) {
  76334. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76335. }
  76336. else {
  76337. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76338. if (radialExplosionEvent) {
  76339. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76340. }
  76341. }
  76342. };
  76343. return PhysicsGravitationalFieldEvent;
  76344. }());
  76345. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76346. /***** Updraft *****/
  76347. var PhysicsUpdraftEvent = /** @class */ (function () {
  76348. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76349. this._scene = _scene;
  76350. this._origin = _origin;
  76351. this._radius = _radius;
  76352. this._strength = _strength;
  76353. this._height = _height;
  76354. this._updraftMode = _updraftMode;
  76355. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76356. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76357. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76358. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76359. this._physicsEngine = this._scene.getPhysicsEngine();
  76360. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76361. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76362. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76363. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76364. }
  76365. this._tickCallback = this._tick.bind(this);
  76366. }
  76367. /**
  76368. * Returns the data related to the updraft event (cylinder).
  76369. * @returns {PhysicsUpdraftEventData}
  76370. */
  76371. PhysicsUpdraftEvent.prototype.getData = function () {
  76372. this._dataFetched = true;
  76373. return {
  76374. cylinder: this._cylinder,
  76375. };
  76376. };
  76377. /**
  76378. * Enables the updraft.
  76379. */
  76380. PhysicsUpdraftEvent.prototype.enable = function () {
  76381. this._tickCallback.call(this);
  76382. this._scene.registerBeforeRender(this._tickCallback);
  76383. };
  76384. /**
  76385. * Disables the cortex.
  76386. */
  76387. PhysicsUpdraftEvent.prototype.disable = function () {
  76388. this._scene.unregisterBeforeRender(this._tickCallback);
  76389. };
  76390. /**
  76391. * Disposes the sphere.
  76392. * @param {bolean} force
  76393. */
  76394. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76395. var _this = this;
  76396. if (force === void 0) { force = true; }
  76397. if (force) {
  76398. this._cylinder.dispose();
  76399. }
  76400. else {
  76401. setTimeout(function () {
  76402. if (!_this._dataFetched) {
  76403. _this._cylinder.dispose();
  76404. }
  76405. }, 0);
  76406. }
  76407. };
  76408. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76409. if (impostor.mass === 0) {
  76410. return null;
  76411. }
  76412. if (!this._intersectsWithCylinder(impostor)) {
  76413. return null;
  76414. }
  76415. var impostorObjectCenter = impostor.getObjectCenter();
  76416. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76417. var direction = this._originDirection;
  76418. }
  76419. else {
  76420. var direction = impostorObjectCenter.subtract(this._originTop);
  76421. }
  76422. var multiplier = this._strength * -1;
  76423. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76424. return { force: force, contactPoint: impostorObjectCenter };
  76425. };
  76426. PhysicsUpdraftEvent.prototype._tick = function () {
  76427. var _this = this;
  76428. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76429. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76430. if (!impostorForceAndContactPoint) {
  76431. return;
  76432. }
  76433. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76434. });
  76435. };
  76436. /*** Helpers ***/
  76437. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76438. if (!this._cylinder) {
  76439. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76440. height: this._height,
  76441. diameter: this._radius * 2,
  76442. }, this._scene);
  76443. this._cylinder.isVisible = false;
  76444. }
  76445. };
  76446. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76447. var impostorObject = impostor.object;
  76448. this._prepareCylinder();
  76449. this._cylinder.position = this._cylinderPosition;
  76450. return this._cylinder.intersectsMesh(impostorObject, true);
  76451. };
  76452. return PhysicsUpdraftEvent;
  76453. }());
  76454. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76455. /***** Vortex *****/
  76456. var PhysicsVortexEvent = /** @class */ (function () {
  76457. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76458. this._scene = _scene;
  76459. this._origin = _origin;
  76460. this._radius = _radius;
  76461. this._strength = _strength;
  76462. this._height = _height;
  76463. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76464. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76465. this._updraftMultiplier = 0.02;
  76466. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76467. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76468. this._physicsEngine = this._scene.getPhysicsEngine();
  76469. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76470. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76471. this._tickCallback = this._tick.bind(this);
  76472. }
  76473. /**
  76474. * Returns the data related to the vortex event (cylinder).
  76475. * @returns {PhysicsVortexEventData}
  76476. */
  76477. PhysicsVortexEvent.prototype.getData = function () {
  76478. this._dataFetched = true;
  76479. return {
  76480. cylinder: this._cylinder,
  76481. };
  76482. };
  76483. /**
  76484. * Enables the vortex.
  76485. */
  76486. PhysicsVortexEvent.prototype.enable = function () {
  76487. this._tickCallback.call(this);
  76488. this._scene.registerBeforeRender(this._tickCallback);
  76489. };
  76490. /**
  76491. * Disables the cortex.
  76492. */
  76493. PhysicsVortexEvent.prototype.disable = function () {
  76494. this._scene.unregisterBeforeRender(this._tickCallback);
  76495. };
  76496. /**
  76497. * Disposes the sphere.
  76498. * @param {bolean} force
  76499. */
  76500. PhysicsVortexEvent.prototype.dispose = function (force) {
  76501. var _this = this;
  76502. if (force === void 0) { force = true; }
  76503. if (force) {
  76504. this._cylinder.dispose();
  76505. }
  76506. else {
  76507. setTimeout(function () {
  76508. if (!_this._dataFetched) {
  76509. _this._cylinder.dispose();
  76510. }
  76511. }, 0);
  76512. }
  76513. };
  76514. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76515. if (impostor.mass === 0) {
  76516. return null;
  76517. }
  76518. if (!this._intersectsWithCylinder(impostor)) {
  76519. return null;
  76520. }
  76521. if (impostor.object.getClassName() !== 'Mesh') {
  76522. return null;
  76523. }
  76524. var impostorObject = impostor.object;
  76525. var impostorObjectCenter = impostor.getObjectCenter();
  76526. 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)
  76527. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76528. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76529. var hit = ray.intersectsMesh(impostorObject);
  76530. var contactPoint = hit.pickedPoint;
  76531. if (!contactPoint) {
  76532. return null;
  76533. }
  76534. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76535. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76536. var directionToOrigin = contactPoint.normalize();
  76537. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76538. directionToOrigin = directionToOrigin.negate();
  76539. }
  76540. // TODO: find a more physically based solution
  76541. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76542. var forceX = directionToOrigin.x * this._strength / 8;
  76543. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76544. var forceZ = directionToOrigin.z * this._strength / 8;
  76545. }
  76546. else {
  76547. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76548. var forceY = this._originTop.y * this._updraftMultiplier;
  76549. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76550. }
  76551. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76552. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76553. return { force: force, contactPoint: impostorObjectCenter };
  76554. };
  76555. PhysicsVortexEvent.prototype._tick = function () {
  76556. var _this = this;
  76557. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76558. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76559. if (!impostorForceAndContactPoint) {
  76560. return;
  76561. }
  76562. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76563. });
  76564. };
  76565. /*** Helpers ***/
  76566. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76567. if (!this._cylinder) {
  76568. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76569. height: this._height,
  76570. diameter: this._radius * 2,
  76571. }, this._scene);
  76572. this._cylinder.isVisible = false;
  76573. }
  76574. };
  76575. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76576. var impostorObject = impostor.object;
  76577. this._prepareCylinder();
  76578. this._cylinder.position = this._cylinderPosition;
  76579. return this._cylinder.intersectsMesh(impostorObject, true);
  76580. };
  76581. return PhysicsVortexEvent;
  76582. }());
  76583. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76584. /***** Enums *****/
  76585. /**
  76586. * The strenght of the force in correspondence to the distance of the affected object
  76587. */
  76588. var PhysicsRadialImpulseFalloff;
  76589. (function (PhysicsRadialImpulseFalloff) {
  76590. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76591. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76592. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76593. /**
  76594. * The strenght of the force in correspondence to the distance of the affected object
  76595. */
  76596. var PhysicsUpdraftMode;
  76597. (function (PhysicsUpdraftMode) {
  76598. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76599. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76600. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76601. })(BABYLON || (BABYLON = {}));
  76602. //# sourceMappingURL=babylon.physicsHelper.js.map
  76603. var BABYLON;
  76604. (function (BABYLON) {
  76605. var CannonJSPlugin = /** @class */ (function () {
  76606. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76607. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76608. if (iterations === void 0) { iterations = 10; }
  76609. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76610. this.name = "CannonJSPlugin";
  76611. this._physicsMaterials = new Array();
  76612. this._fixedTimeStep = 1 / 60;
  76613. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76614. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76615. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76616. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76617. this._tmpPosition = BABYLON.Vector3.Zero();
  76618. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76619. this._tmpUnityRotation = new BABYLON.Quaternion();
  76620. if (!this.isSupported()) {
  76621. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76622. return;
  76623. }
  76624. this._extendNamespace();
  76625. this.world = new this.BJSCANNON.World();
  76626. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76627. this.world.solver.iterations = iterations;
  76628. }
  76629. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76630. this.world.gravity.copy(gravity);
  76631. };
  76632. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76633. this._fixedTimeStep = timeStep;
  76634. };
  76635. CannonJSPlugin.prototype.getTimeStep = function () {
  76636. return this._fixedTimeStep;
  76637. };
  76638. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76639. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76640. };
  76641. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76642. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76643. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76644. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76645. };
  76646. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76647. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76648. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76649. impostor.physicsBody.applyForce(impulse, worldPoint);
  76650. };
  76651. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76652. //parent-child relationship. Does this impostor has a parent impostor?
  76653. if (impostor.parent) {
  76654. if (impostor.physicsBody) {
  76655. this.removePhysicsBody(impostor);
  76656. //TODO is that needed?
  76657. impostor.forceUpdate();
  76658. }
  76659. return;
  76660. }
  76661. //should a new body be created for this impostor?
  76662. if (impostor.isBodyInitRequired()) {
  76663. var shape = this._createShape(impostor);
  76664. //unregister events, if body is being changed
  76665. var oldBody = impostor.physicsBody;
  76666. if (oldBody) {
  76667. this.removePhysicsBody(impostor);
  76668. }
  76669. //create the body and material
  76670. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76671. var bodyCreationObject = {
  76672. mass: impostor.getParam("mass"),
  76673. material: material
  76674. };
  76675. // A simple extend, in case native options were used.
  76676. var nativeOptions = impostor.getParam("nativeOptions");
  76677. for (var key in nativeOptions) {
  76678. if (nativeOptions.hasOwnProperty(key)) {
  76679. bodyCreationObject[key] = nativeOptions[key];
  76680. }
  76681. }
  76682. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76683. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76684. this.world.addEventListener("preStep", impostor.beforeStep);
  76685. this.world.addEventListener("postStep", impostor.afterStep);
  76686. impostor.physicsBody.addShape(shape);
  76687. this.world.add(impostor.physicsBody);
  76688. //try to keep the body moving in the right direction by taking old properties.
  76689. //Should be tested!
  76690. if (oldBody) {
  76691. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76692. impostor.physicsBody[param].copy(oldBody[param]);
  76693. });
  76694. }
  76695. this._processChildMeshes(impostor);
  76696. }
  76697. //now update the body's transformation
  76698. this._updatePhysicsBodyTransformation(impostor);
  76699. };
  76700. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76701. var _this = this;
  76702. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76703. var currentRotation = mainImpostor.object.rotationQuaternion;
  76704. if (meshChildren.length) {
  76705. var processMesh = function (localPosition, mesh) {
  76706. if (!currentRotation || !mesh.rotationQuaternion) {
  76707. return;
  76708. }
  76709. var childImpostor = mesh.getPhysicsImpostor();
  76710. if (childImpostor) {
  76711. var parent = childImpostor.parent;
  76712. if (parent !== mainImpostor) {
  76713. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76714. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76715. if (childImpostor.physicsBody) {
  76716. _this.removePhysicsBody(childImpostor);
  76717. childImpostor.physicsBody = null;
  76718. }
  76719. childImpostor.parent = mainImpostor;
  76720. childImpostor.resetUpdateFlags();
  76721. 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));
  76722. //Add the mass of the children.
  76723. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76724. }
  76725. }
  76726. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76727. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76728. };
  76729. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76730. }
  76731. };
  76732. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76733. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76734. this.world.removeEventListener("preStep", impostor.beforeStep);
  76735. this.world.removeEventListener("postStep", impostor.afterStep);
  76736. this.world.remove(impostor.physicsBody);
  76737. };
  76738. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76739. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76740. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76741. if (!mainBody || !connectedBody) {
  76742. return;
  76743. }
  76744. var constraint;
  76745. var jointData = impostorJoint.joint.jointData;
  76746. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76747. var constraintData = {
  76748. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76749. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76750. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76751. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76752. maxForce: jointData.nativeParams.maxForce,
  76753. collideConnected: !!jointData.collision
  76754. };
  76755. switch (impostorJoint.joint.type) {
  76756. case BABYLON.PhysicsJoint.HingeJoint:
  76757. case BABYLON.PhysicsJoint.Hinge2Joint:
  76758. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76759. break;
  76760. case BABYLON.PhysicsJoint.DistanceJoint:
  76761. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76762. break;
  76763. case BABYLON.PhysicsJoint.SpringJoint:
  76764. var springData = jointData;
  76765. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76766. restLength: springData.length,
  76767. stiffness: springData.stiffness,
  76768. damping: springData.damping,
  76769. localAnchorA: constraintData.pivotA,
  76770. localAnchorB: constraintData.pivotB
  76771. });
  76772. break;
  76773. case BABYLON.PhysicsJoint.LockJoint:
  76774. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76775. break;
  76776. case BABYLON.PhysicsJoint.PointToPointJoint:
  76777. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76778. default:
  76779. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76780. break;
  76781. }
  76782. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76783. constraint.collideConnected = !!jointData.collision;
  76784. impostorJoint.joint.physicsJoint = constraint;
  76785. //don't add spring as constraint, as it is not one.
  76786. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76787. this.world.addConstraint(constraint);
  76788. }
  76789. else {
  76790. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76791. constraint.applyForce();
  76792. });
  76793. }
  76794. };
  76795. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76796. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76797. };
  76798. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76799. var index;
  76800. var mat;
  76801. for (index = 0; index < this._physicsMaterials.length; index++) {
  76802. mat = this._physicsMaterials[index];
  76803. if (mat.friction === friction && mat.restitution === restitution) {
  76804. return mat;
  76805. }
  76806. }
  76807. var currentMat = new this.BJSCANNON.Material(name);
  76808. currentMat.friction = friction;
  76809. currentMat.restitution = restitution;
  76810. this._physicsMaterials.push(currentMat);
  76811. return currentMat;
  76812. };
  76813. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76814. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76815. };
  76816. CannonJSPlugin.prototype._createShape = function (impostor) {
  76817. var object = impostor.object;
  76818. var returnValue;
  76819. var extendSize = impostor.getObjectExtendSize();
  76820. switch (impostor.type) {
  76821. case BABYLON.PhysicsImpostor.SphereImpostor:
  76822. var radiusX = extendSize.x;
  76823. var radiusY = extendSize.y;
  76824. var radiusZ = extendSize.z;
  76825. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76826. break;
  76827. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76828. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76829. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76830. break;
  76831. case BABYLON.PhysicsImpostor.BoxImpostor:
  76832. var box = extendSize.scale(0.5);
  76833. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76834. break;
  76835. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76836. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76837. returnValue = new this.BJSCANNON.Plane();
  76838. break;
  76839. case BABYLON.PhysicsImpostor.MeshImpostor:
  76840. // should transform the vertex data to world coordinates!!
  76841. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76842. var rawFaces = object.getIndices ? object.getIndices() : [];
  76843. if (!rawVerts)
  76844. return;
  76845. // get only scale! so the object could transform correctly.
  76846. var oldPosition = object.position.clone();
  76847. var oldRotation = object.rotation && object.rotation.clone();
  76848. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76849. object.position.copyFromFloats(0, 0, 0);
  76850. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76851. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76852. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76853. var transform = object.computeWorldMatrix(true);
  76854. // convert rawVerts to object space
  76855. var temp = new Array();
  76856. var index;
  76857. for (index = 0; index < rawVerts.length; index += 3) {
  76858. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76859. }
  76860. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76861. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76862. //now set back the transformation!
  76863. object.position.copyFrom(oldPosition);
  76864. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76865. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76866. break;
  76867. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76868. var oldPosition2 = object.position.clone();
  76869. var oldRotation2 = object.rotation && object.rotation.clone();
  76870. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76871. object.position.copyFromFloats(0, 0, 0);
  76872. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76873. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76874. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76875. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76876. returnValue = this._createHeightmap(object);
  76877. object.position.copyFrom(oldPosition2);
  76878. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76879. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76880. object.computeWorldMatrix(true);
  76881. break;
  76882. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76883. returnValue = new this.BJSCANNON.Particle();
  76884. break;
  76885. }
  76886. return returnValue;
  76887. };
  76888. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76889. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76890. var transform = object.computeWorldMatrix(true);
  76891. // convert rawVerts to object space
  76892. var temp = new Array();
  76893. var index;
  76894. for (index = 0; index < pos.length; index += 3) {
  76895. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76896. }
  76897. pos = temp;
  76898. var matrix = new Array();
  76899. //For now pointDepth will not be used and will be automatically calculated.
  76900. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76901. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76902. var boundingInfo = object.getBoundingInfo();
  76903. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76904. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76905. var elementSize = dim * 2 / arraySize;
  76906. for (var i = 0; i < pos.length; i = i + 3) {
  76907. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76908. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76909. var y = -pos[i + 2] + minY;
  76910. if (!matrix[x]) {
  76911. matrix[x] = [];
  76912. }
  76913. if (!matrix[x][z]) {
  76914. matrix[x][z] = y;
  76915. }
  76916. matrix[x][z] = Math.max(y, matrix[x][z]);
  76917. }
  76918. for (var x = 0; x <= arraySize; ++x) {
  76919. if (!matrix[x]) {
  76920. var loc = 1;
  76921. while (!matrix[(x + loc) % arraySize]) {
  76922. loc++;
  76923. }
  76924. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76925. //console.log("missing x", x);
  76926. }
  76927. for (var z = 0; z <= arraySize; ++z) {
  76928. if (!matrix[x][z]) {
  76929. var loc = 1;
  76930. var newValue;
  76931. while (newValue === undefined) {
  76932. newValue = matrix[x][(z + loc++) % arraySize];
  76933. }
  76934. matrix[x][z] = newValue;
  76935. }
  76936. }
  76937. }
  76938. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76939. elementSize: elementSize
  76940. });
  76941. //For future reference, needed for body transformation
  76942. shape.minY = minY;
  76943. return shape;
  76944. };
  76945. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76946. var object = impostor.object;
  76947. //make sure it is updated...
  76948. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76949. // The delta between the mesh position and the mesh bounding box center
  76950. var bInfo = object.getBoundingInfo();
  76951. if (!bInfo)
  76952. return;
  76953. var center = impostor.getObjectCenter();
  76954. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76955. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76956. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76957. this._tmpPosition.copyFrom(center);
  76958. var quaternion = object.rotationQuaternion;
  76959. if (!quaternion) {
  76960. return;
  76961. }
  76962. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76963. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76964. //-90 DEG in X, precalculated
  76965. quaternion = quaternion.multiply(this._minus90X);
  76966. //Invert! (Precalculated, 90 deg in X)
  76967. //No need to clone. this will never change.
  76968. impostor.setDeltaRotation(this._plus90X);
  76969. }
  76970. //If it is a heightfield, if should be centered.
  76971. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76972. var mesh = object;
  76973. var boundingInfo = mesh.getBoundingInfo();
  76974. //calculate the correct body position:
  76975. var rotationQuaternion = mesh.rotationQuaternion;
  76976. mesh.rotationQuaternion = this._tmpUnityRotation;
  76977. mesh.computeWorldMatrix(true);
  76978. //get original center with no rotation
  76979. var c = center.clone();
  76980. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76981. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76982. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76983. mesh.setPreTransformMatrix(p);
  76984. mesh.computeWorldMatrix(true);
  76985. //calculate the translation
  76986. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76987. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76988. //add it inverted to the delta
  76989. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76990. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76991. //rotation is back
  76992. mesh.rotationQuaternion = rotationQuaternion;
  76993. mesh.setPreTransformMatrix(oldPivot);
  76994. mesh.computeWorldMatrix(true);
  76995. }
  76996. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76997. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76998. //this._tmpPosition.copyFrom(object.position);
  76999. }
  77000. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77001. //Now update the impostor object
  77002. impostor.physicsBody.position.copy(this._tmpPosition);
  77003. impostor.physicsBody.quaternion.copy(quaternion);
  77004. };
  77005. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77006. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77007. if (impostor.object.rotationQuaternion) {
  77008. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77009. }
  77010. };
  77011. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77012. impostor.physicsBody.position.copy(newPosition);
  77013. impostor.physicsBody.quaternion.copy(newRotation);
  77014. };
  77015. CannonJSPlugin.prototype.isSupported = function () {
  77016. return this.BJSCANNON !== undefined;
  77017. };
  77018. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77019. impostor.physicsBody.velocity.copy(velocity);
  77020. };
  77021. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77022. impostor.physicsBody.angularVelocity.copy(velocity);
  77023. };
  77024. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77025. var v = impostor.physicsBody.velocity;
  77026. if (!v) {
  77027. return null;
  77028. }
  77029. return new BABYLON.Vector3(v.x, v.y, v.z);
  77030. };
  77031. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77032. var v = impostor.physicsBody.angularVelocity;
  77033. if (!v) {
  77034. return null;
  77035. }
  77036. return new BABYLON.Vector3(v.x, v.y, v.z);
  77037. };
  77038. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77039. impostor.physicsBody.mass = mass;
  77040. impostor.physicsBody.updateMassProperties();
  77041. };
  77042. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77043. return impostor.physicsBody.mass;
  77044. };
  77045. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77046. return impostor.physicsBody.material.friction;
  77047. };
  77048. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77049. impostor.physicsBody.material.friction = friction;
  77050. };
  77051. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77052. return impostor.physicsBody.material.restitution;
  77053. };
  77054. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77055. impostor.physicsBody.material.restitution = restitution;
  77056. };
  77057. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77058. impostor.physicsBody.sleep();
  77059. };
  77060. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77061. impostor.physicsBody.wakeUp();
  77062. };
  77063. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77064. joint.physicsJoint.distance = maxDistance;
  77065. };
  77066. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77067. // if (!motorIndex) {
  77068. // joint.physicsJoint.enableMotor();
  77069. // }
  77070. // }
  77071. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77072. // if (!motorIndex) {
  77073. // joint.physicsJoint.disableMotor();
  77074. // }
  77075. // }
  77076. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77077. if (!motorIndex) {
  77078. joint.physicsJoint.enableMotor();
  77079. joint.physicsJoint.setMotorSpeed(speed);
  77080. if (maxForce) {
  77081. this.setLimit(joint, maxForce);
  77082. }
  77083. }
  77084. };
  77085. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77086. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77087. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77088. };
  77089. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77090. var body = impostor.physicsBody;
  77091. mesh.position.x = body.position.x;
  77092. mesh.position.y = body.position.y;
  77093. mesh.position.z = body.position.z;
  77094. if (mesh.rotationQuaternion) {
  77095. mesh.rotationQuaternion.x = body.quaternion.x;
  77096. mesh.rotationQuaternion.y = body.quaternion.y;
  77097. mesh.rotationQuaternion.z = body.quaternion.z;
  77098. mesh.rotationQuaternion.w = body.quaternion.w;
  77099. }
  77100. };
  77101. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77102. var shape = impostor.physicsBody.shapes[0];
  77103. return shape.boundingSphereRadius;
  77104. };
  77105. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77106. var shape = impostor.physicsBody.shapes[0];
  77107. result.x = shape.halfExtents.x * 2;
  77108. result.y = shape.halfExtents.y * 2;
  77109. result.z = shape.halfExtents.z * 2;
  77110. };
  77111. CannonJSPlugin.prototype.dispose = function () {
  77112. };
  77113. CannonJSPlugin.prototype._extendNamespace = function () {
  77114. //this will force cannon to execute at least one step when using interpolation
  77115. var step_tmp1 = new this.BJSCANNON.Vec3();
  77116. var Engine = this.BJSCANNON;
  77117. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77118. maxSubSteps = maxSubSteps || 10;
  77119. timeSinceLastCalled = timeSinceLastCalled || 0;
  77120. if (timeSinceLastCalled === 0) {
  77121. this.internalStep(dt);
  77122. this.time += dt;
  77123. }
  77124. else {
  77125. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77126. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77127. var t0 = performance.now();
  77128. for (var i = 0; i !== internalSteps; i++) {
  77129. this.internalStep(dt);
  77130. if (performance.now() - t0 > dt * 1000) {
  77131. break;
  77132. }
  77133. }
  77134. this.time += timeSinceLastCalled;
  77135. var h = this.time % dt;
  77136. var h_div_dt = h / dt;
  77137. var interpvelo = step_tmp1;
  77138. var bodies = this.bodies;
  77139. for (var j = 0; j !== bodies.length; j++) {
  77140. var b = bodies[j];
  77141. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77142. b.position.vsub(b.previousPosition, interpvelo);
  77143. interpvelo.scale(h_div_dt, interpvelo);
  77144. b.position.vadd(interpvelo, b.interpolatedPosition);
  77145. }
  77146. else {
  77147. b.interpolatedPosition.copy(b.position);
  77148. b.interpolatedQuaternion.copy(b.quaternion);
  77149. }
  77150. }
  77151. }
  77152. };
  77153. };
  77154. return CannonJSPlugin;
  77155. }());
  77156. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77157. })(BABYLON || (BABYLON = {}));
  77158. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77159. var BABYLON;
  77160. (function (BABYLON) {
  77161. var OimoJSPlugin = /** @class */ (function () {
  77162. function OimoJSPlugin(iterations) {
  77163. this.name = "OimoJSPlugin";
  77164. this._tmpImpostorsArray = [];
  77165. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77166. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  77167. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77168. this.world.worldscale(1);
  77169. this.world.clear();
  77170. //making sure no stats are calculated
  77171. this.world.isNoStat = true;
  77172. }
  77173. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77174. this.world.gravity.copy(gravity);
  77175. };
  77176. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77177. this.world.timeStep = timeStep;
  77178. };
  77179. OimoJSPlugin.prototype.getTimeStep = function () {
  77180. return this.world.timeStep;
  77181. };
  77182. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77183. var _this = this;
  77184. impostors.forEach(function (impostor) {
  77185. impostor.beforeStep();
  77186. });
  77187. this.world.step();
  77188. impostors.forEach(function (impostor) {
  77189. impostor.afterStep();
  77190. //update the ordered impostors array
  77191. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77192. });
  77193. //check for collisions
  77194. var contact = this.world.contacts;
  77195. while (contact !== null) {
  77196. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77197. contact = contact.next;
  77198. continue;
  77199. }
  77200. //is this body colliding with any other? get the impostor
  77201. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77202. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77203. if (!mainImpostor || !collidingImpostor) {
  77204. contact = contact.next;
  77205. continue;
  77206. }
  77207. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77208. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77209. contact = contact.next;
  77210. }
  77211. };
  77212. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77213. var mass = impostor.physicsBody.massInfo.mass;
  77214. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77215. };
  77216. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77217. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77218. this.applyImpulse(impostor, force, contactPoint);
  77219. };
  77220. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77221. var _this = this;
  77222. //parent-child relationship. Does this impostor has a parent impostor?
  77223. if (impostor.parent) {
  77224. if (impostor.physicsBody) {
  77225. this.removePhysicsBody(impostor);
  77226. //TODO is that needed?
  77227. impostor.forceUpdate();
  77228. }
  77229. return;
  77230. }
  77231. if (impostor.isBodyInitRequired()) {
  77232. var bodyConfig = {
  77233. name: impostor.uniqueId,
  77234. //Oimo must have mass, also for static objects.
  77235. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77236. size: [],
  77237. type: [],
  77238. pos: [],
  77239. rot: [],
  77240. move: impostor.getParam("mass") !== 0,
  77241. //Supporting older versions of Oimo
  77242. world: this.world
  77243. };
  77244. var impostors = [impostor];
  77245. var addToArray = function (parent) {
  77246. if (!parent.getChildMeshes)
  77247. return;
  77248. parent.getChildMeshes().forEach(function (m) {
  77249. if (m.physicsImpostor) {
  77250. impostors.push(m.physicsImpostor);
  77251. //m.physicsImpostor._init();
  77252. }
  77253. });
  77254. };
  77255. addToArray(impostor.object);
  77256. var checkWithEpsilon_1 = function (value) {
  77257. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77258. };
  77259. impostors.forEach(function (i) {
  77260. if (!impostor.object.rotationQuaternion) {
  77261. return;
  77262. }
  77263. //get the correct bounding box
  77264. var oldQuaternion = i.object.rotationQuaternion;
  77265. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77266. x: impostor.object.rotationQuaternion.x,
  77267. y: impostor.object.rotationQuaternion.y,
  77268. z: impostor.object.rotationQuaternion.z,
  77269. s: impostor.object.rotationQuaternion.w
  77270. });
  77271. var extendSize = i.getObjectExtendSize();
  77272. if (i === impostor) {
  77273. var center = impostor.getObjectCenter();
  77274. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77275. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77276. //Can also use Array.prototype.push.apply
  77277. bodyConfig.pos.push(center.x);
  77278. bodyConfig.pos.push(center.y);
  77279. bodyConfig.pos.push(center.z);
  77280. //tmp solution
  77281. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77282. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77283. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77284. }
  77285. else {
  77286. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77287. bodyConfig.pos.push(localPosition.x);
  77288. bodyConfig.pos.push(localPosition.y);
  77289. bodyConfig.pos.push(localPosition.z);
  77290. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77291. bodyConfig.rot.push(0);
  77292. bodyConfig.rot.push(0);
  77293. bodyConfig.rot.push(0);
  77294. }
  77295. // register mesh
  77296. switch (i.type) {
  77297. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77298. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77299. case BABYLON.PhysicsImpostor.SphereImpostor:
  77300. var radiusX = extendSize.x;
  77301. var radiusY = extendSize.y;
  77302. var radiusZ = extendSize.z;
  77303. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77304. bodyConfig.type.push('sphere');
  77305. //due to the way oimo works with compounds, add 3 times
  77306. bodyConfig.size.push(size);
  77307. bodyConfig.size.push(size);
  77308. bodyConfig.size.push(size);
  77309. break;
  77310. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77311. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77312. var sizeY = checkWithEpsilon_1(extendSize.y);
  77313. bodyConfig.type.push('cylinder');
  77314. bodyConfig.size.push(sizeX);
  77315. bodyConfig.size.push(sizeY);
  77316. //due to the way oimo works with compounds, add one more value.
  77317. bodyConfig.size.push(sizeY);
  77318. break;
  77319. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77320. case BABYLON.PhysicsImpostor.BoxImpostor:
  77321. default:
  77322. var sizeX = checkWithEpsilon_1(extendSize.x);
  77323. var sizeY = checkWithEpsilon_1(extendSize.y);
  77324. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77325. bodyConfig.type.push('box');
  77326. bodyConfig.size.push(sizeX);
  77327. bodyConfig.size.push(sizeY);
  77328. bodyConfig.size.push(sizeZ);
  77329. break;
  77330. }
  77331. //actually not needed, but hey...
  77332. i.object.rotationQuaternion = oldQuaternion;
  77333. });
  77334. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77335. }
  77336. else {
  77337. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77338. }
  77339. impostor.setDeltaPosition(this._tmpPositionVector);
  77340. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77341. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77342. };
  77343. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77344. //impostor.physicsBody.dispose();
  77345. //Same as : (older oimo versions)
  77346. this.world.removeRigidBody(impostor.physicsBody);
  77347. };
  77348. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77349. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77350. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77351. if (!mainBody || !connectedBody) {
  77352. return;
  77353. }
  77354. var jointData = impostorJoint.joint.jointData;
  77355. var options = jointData.nativeParams || {};
  77356. var type;
  77357. var nativeJointData = {
  77358. body1: mainBody,
  77359. body2: connectedBody,
  77360. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77361. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77362. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77363. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77364. min: options.min,
  77365. max: options.max,
  77366. collision: options.collision || jointData.collision,
  77367. spring: options.spring,
  77368. //supporting older version of Oimo
  77369. world: this.world
  77370. };
  77371. switch (impostorJoint.joint.type) {
  77372. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77373. type = "jointBall";
  77374. break;
  77375. case BABYLON.PhysicsJoint.SpringJoint:
  77376. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77377. var springData = jointData;
  77378. nativeJointData.min = springData.length || nativeJointData.min;
  77379. //Max should also be set, just make sure it is at least min
  77380. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77381. case BABYLON.PhysicsJoint.DistanceJoint:
  77382. type = "jointDistance";
  77383. nativeJointData.max = jointData.maxDistance;
  77384. break;
  77385. case BABYLON.PhysicsJoint.PrismaticJoint:
  77386. type = "jointPrisme";
  77387. break;
  77388. case BABYLON.PhysicsJoint.SliderJoint:
  77389. type = "jointSlide";
  77390. break;
  77391. case BABYLON.PhysicsJoint.WheelJoint:
  77392. type = "jointWheel";
  77393. break;
  77394. case BABYLON.PhysicsJoint.HingeJoint:
  77395. default:
  77396. type = "jointHinge";
  77397. break;
  77398. }
  77399. nativeJointData.type = type;
  77400. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77401. };
  77402. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77403. //Bug in Oimo prevents us from disposing a joint in the playground
  77404. //joint.joint.physicsJoint.dispose();
  77405. //So we will bruteforce it!
  77406. try {
  77407. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77408. }
  77409. catch (e) {
  77410. BABYLON.Tools.Warn(e);
  77411. }
  77412. };
  77413. OimoJSPlugin.prototype.isSupported = function () {
  77414. return this.BJSOIMO !== undefined;
  77415. };
  77416. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77417. if (!impostor.physicsBody.sleeping) {
  77418. //TODO check that
  77419. if (impostor.physicsBody.shapes.next) {
  77420. var parentShape = this._getLastShape(impostor.physicsBody);
  77421. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77422. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77423. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77424. }
  77425. else {
  77426. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77427. }
  77428. if (impostor.object.rotationQuaternion) {
  77429. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77430. impostor.object.rotationQuaternion.normalize();
  77431. }
  77432. }
  77433. };
  77434. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77435. var body = impostor.physicsBody;
  77436. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77437. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77438. body.syncShapes();
  77439. body.awake();
  77440. };
  77441. OimoJSPlugin.prototype._getLastShape = function (body) {
  77442. var lastShape = body.shapes;
  77443. while (lastShape.next) {
  77444. lastShape = lastShape.next;
  77445. }
  77446. return lastShape;
  77447. };
  77448. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77449. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77450. };
  77451. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77452. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77453. };
  77454. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77455. var v = impostor.physicsBody.linearVelocity;
  77456. if (!v) {
  77457. return null;
  77458. }
  77459. return new BABYLON.Vector3(v.x, v.y, v.z);
  77460. };
  77461. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77462. var v = impostor.physicsBody.angularVelocity;
  77463. if (!v) {
  77464. return null;
  77465. }
  77466. return new BABYLON.Vector3(v.x, v.y, v.z);
  77467. };
  77468. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77469. var staticBody = mass === 0;
  77470. //this will actually set the body's density and not its mass.
  77471. //But this is how oimo treats the mass variable.
  77472. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77473. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77474. };
  77475. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77476. return impostor.physicsBody.shapes.density;
  77477. };
  77478. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77479. return impostor.physicsBody.shapes.friction;
  77480. };
  77481. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77482. impostor.physicsBody.shapes.friction = friction;
  77483. };
  77484. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77485. return impostor.physicsBody.shapes.restitution;
  77486. };
  77487. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77488. impostor.physicsBody.shapes.restitution = restitution;
  77489. };
  77490. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77491. impostor.physicsBody.sleep();
  77492. };
  77493. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77494. impostor.physicsBody.awake();
  77495. };
  77496. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77497. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77498. if (minDistance !== void 0) {
  77499. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77500. }
  77501. };
  77502. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77503. //TODO separate rotational and transational motors.
  77504. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77505. if (motor) {
  77506. motor.setMotor(speed, maxForce);
  77507. }
  77508. };
  77509. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77510. //TODO separate rotational and transational motors.
  77511. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77512. if (motor) {
  77513. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77514. }
  77515. };
  77516. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77517. var body = impostor.physicsBody;
  77518. mesh.position.x = body.position.x;
  77519. mesh.position.y = body.position.y;
  77520. mesh.position.z = body.position.z;
  77521. if (mesh.rotationQuaternion) {
  77522. mesh.rotationQuaternion.x = body.orientation.x;
  77523. mesh.rotationQuaternion.y = body.orientation.y;
  77524. mesh.rotationQuaternion.z = body.orientation.z;
  77525. mesh.rotationQuaternion.w = body.orientation.s;
  77526. }
  77527. };
  77528. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77529. return impostor.physicsBody.shapes.radius;
  77530. };
  77531. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77532. var shape = impostor.physicsBody.shapes;
  77533. result.x = shape.halfWidth * 2;
  77534. result.y = shape.halfHeight * 2;
  77535. result.z = shape.halfDepth * 2;
  77536. };
  77537. OimoJSPlugin.prototype.dispose = function () {
  77538. this.world.clear();
  77539. };
  77540. return OimoJSPlugin;
  77541. }());
  77542. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77543. })(BABYLON || (BABYLON = {}));
  77544. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77545. var BABYLON;
  77546. (function (BABYLON) {
  77547. /*
  77548. * Based on jsTGALoader - Javascript loader for TGA file
  77549. * By Vincent Thibault
  77550. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77551. */
  77552. var TGATools = /** @class */ (function () {
  77553. function TGATools() {
  77554. }
  77555. TGATools.GetTGAHeader = function (data) {
  77556. var offset = 0;
  77557. var header = {
  77558. id_length: data[offset++],
  77559. colormap_type: data[offset++],
  77560. image_type: data[offset++],
  77561. colormap_index: data[offset++] | data[offset++] << 8,
  77562. colormap_length: data[offset++] | data[offset++] << 8,
  77563. colormap_size: data[offset++],
  77564. origin: [
  77565. data[offset++] | data[offset++] << 8,
  77566. data[offset++] | data[offset++] << 8
  77567. ],
  77568. width: data[offset++] | data[offset++] << 8,
  77569. height: data[offset++] | data[offset++] << 8,
  77570. pixel_size: data[offset++],
  77571. flags: data[offset++]
  77572. };
  77573. return header;
  77574. };
  77575. TGATools.UploadContent = function (gl, data) {
  77576. // Not enough data to contain header ?
  77577. if (data.length < 19) {
  77578. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77579. return;
  77580. }
  77581. // Read Header
  77582. var offset = 18;
  77583. var header = TGATools.GetTGAHeader(data);
  77584. // Assume it's a valid Targa file.
  77585. if (header.id_length + offset > data.length) {
  77586. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77587. return;
  77588. }
  77589. // Skip not needed data
  77590. offset += header.id_length;
  77591. var use_rle = false;
  77592. var use_pal = false;
  77593. var use_grey = false;
  77594. // Get some informations.
  77595. switch (header.image_type) {
  77596. case TGATools._TYPE_RLE_INDEXED:
  77597. use_rle = true;
  77598. case TGATools._TYPE_INDEXED:
  77599. use_pal = true;
  77600. break;
  77601. case TGATools._TYPE_RLE_RGB:
  77602. use_rle = true;
  77603. case TGATools._TYPE_RGB:
  77604. // use_rgb = true;
  77605. break;
  77606. case TGATools._TYPE_RLE_GREY:
  77607. use_rle = true;
  77608. case TGATools._TYPE_GREY:
  77609. use_grey = true;
  77610. break;
  77611. }
  77612. var pixel_data;
  77613. // var numAlphaBits = header.flags & 0xf;
  77614. var pixel_size = header.pixel_size >> 3;
  77615. var pixel_total = header.width * header.height * pixel_size;
  77616. // Read palettes
  77617. var palettes;
  77618. if (use_pal) {
  77619. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77620. }
  77621. // Read LRE
  77622. if (use_rle) {
  77623. pixel_data = new Uint8Array(pixel_total);
  77624. var c, count, i;
  77625. var localOffset = 0;
  77626. var pixels = new Uint8Array(pixel_size);
  77627. while (offset < pixel_total && localOffset < pixel_total) {
  77628. c = data[offset++];
  77629. count = (c & 0x7f) + 1;
  77630. // RLE pixels
  77631. if (c & 0x80) {
  77632. // Bind pixel tmp array
  77633. for (i = 0; i < pixel_size; ++i) {
  77634. pixels[i] = data[offset++];
  77635. }
  77636. // Copy pixel array
  77637. for (i = 0; i < count; ++i) {
  77638. pixel_data.set(pixels, localOffset + i * pixel_size);
  77639. }
  77640. localOffset += pixel_size * count;
  77641. }
  77642. else {
  77643. count *= pixel_size;
  77644. for (i = 0; i < count; ++i) {
  77645. pixel_data[localOffset + i] = data[offset++];
  77646. }
  77647. localOffset += count;
  77648. }
  77649. }
  77650. }
  77651. else {
  77652. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77653. }
  77654. // Load to texture
  77655. var x_start, y_start, x_step, y_step, y_end, x_end;
  77656. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77657. default:
  77658. case TGATools._ORIGIN_UL:
  77659. x_start = 0;
  77660. x_step = 1;
  77661. x_end = header.width;
  77662. y_start = 0;
  77663. y_step = 1;
  77664. y_end = header.height;
  77665. break;
  77666. case TGATools._ORIGIN_BL:
  77667. x_start = 0;
  77668. x_step = 1;
  77669. x_end = header.width;
  77670. y_start = header.height - 1;
  77671. y_step = -1;
  77672. y_end = -1;
  77673. break;
  77674. case TGATools._ORIGIN_UR:
  77675. x_start = header.width - 1;
  77676. x_step = -1;
  77677. x_end = -1;
  77678. y_start = 0;
  77679. y_step = 1;
  77680. y_end = header.height;
  77681. break;
  77682. case TGATools._ORIGIN_BR:
  77683. x_start = header.width - 1;
  77684. x_step = -1;
  77685. x_end = -1;
  77686. y_start = header.height - 1;
  77687. y_step = -1;
  77688. y_end = -1;
  77689. break;
  77690. }
  77691. // Load the specify method
  77692. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77693. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77694. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77695. };
  77696. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77697. var image = pixel_data, colormap = palettes;
  77698. var width = header.width, height = header.height;
  77699. var color, i = 0, x, y;
  77700. var imageData = new Uint8Array(width * height * 4);
  77701. for (y = y_start; y !== y_end; y += y_step) {
  77702. for (x = x_start; x !== x_end; x += x_step, i++) {
  77703. color = image[i];
  77704. imageData[(x + width * y) * 4 + 3] = 255;
  77705. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77706. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77707. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77708. }
  77709. }
  77710. return imageData;
  77711. };
  77712. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77713. var image = pixel_data;
  77714. var width = header.width, height = header.height;
  77715. var color, i = 0, x, y;
  77716. var imageData = new Uint8Array(width * height * 4);
  77717. for (y = y_start; y !== y_end; y += y_step) {
  77718. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77719. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77720. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  77721. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  77722. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  77723. imageData[(x + width * y) * 4 + 0] = r;
  77724. imageData[(x + width * y) * 4 + 1] = g;
  77725. imageData[(x + width * y) * 4 + 2] = b;
  77726. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77727. }
  77728. }
  77729. return imageData;
  77730. };
  77731. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77732. var image = pixel_data;
  77733. var width = header.width, height = header.height;
  77734. var i = 0, x, y;
  77735. var imageData = new Uint8Array(width * height * 4);
  77736. for (y = y_start; y !== y_end; y += y_step) {
  77737. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77738. imageData[(x + width * y) * 4 + 3] = 255;
  77739. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77740. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77741. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77742. }
  77743. }
  77744. return imageData;
  77745. };
  77746. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77747. var image = pixel_data;
  77748. var width = header.width, height = header.height;
  77749. var i = 0, x, y;
  77750. var imageData = new Uint8Array(width * height * 4);
  77751. for (y = y_start; y !== y_end; y += y_step) {
  77752. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77753. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77754. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77755. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77756. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77757. }
  77758. }
  77759. return imageData;
  77760. };
  77761. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77762. var image = pixel_data;
  77763. var width = header.width, height = header.height;
  77764. var color, i = 0, x, y;
  77765. var imageData = new Uint8Array(width * height * 4);
  77766. for (y = y_start; y !== y_end; y += y_step) {
  77767. for (x = x_start; x !== x_end; x += x_step, i++) {
  77768. color = image[i];
  77769. imageData[(x + width * y) * 4 + 0] = color;
  77770. imageData[(x + width * y) * 4 + 1] = color;
  77771. imageData[(x + width * y) * 4 + 2] = color;
  77772. imageData[(x + width * y) * 4 + 3] = 255;
  77773. }
  77774. }
  77775. return imageData;
  77776. };
  77777. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77778. var image = pixel_data;
  77779. var width = header.width, height = header.height;
  77780. var i = 0, x, y;
  77781. var imageData = new Uint8Array(width * height * 4);
  77782. for (y = y_start; y !== y_end; y += y_step) {
  77783. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77784. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77785. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77786. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77787. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77788. }
  77789. }
  77790. return imageData;
  77791. };
  77792. //private static _TYPE_NO_DATA = 0;
  77793. TGATools._TYPE_INDEXED = 1;
  77794. TGATools._TYPE_RGB = 2;
  77795. TGATools._TYPE_GREY = 3;
  77796. TGATools._TYPE_RLE_INDEXED = 9;
  77797. TGATools._TYPE_RLE_RGB = 10;
  77798. TGATools._TYPE_RLE_GREY = 11;
  77799. TGATools._ORIGIN_MASK = 0x30;
  77800. TGATools._ORIGIN_SHIFT = 0x04;
  77801. TGATools._ORIGIN_BL = 0x00;
  77802. TGATools._ORIGIN_BR = 0x01;
  77803. TGATools._ORIGIN_UL = 0x02;
  77804. TGATools._ORIGIN_UR = 0x03;
  77805. return TGATools;
  77806. }());
  77807. BABYLON.TGATools = TGATools;
  77808. })(BABYLON || (BABYLON = {}));
  77809. //# sourceMappingURL=babylon.tga.js.map
  77810. var BABYLON;
  77811. (function (BABYLON) {
  77812. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77813. // All values and structures referenced from:
  77814. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77815. var DDS_MAGIC = 0x20534444;
  77816. var
  77817. //DDSD_CAPS = 0x1,
  77818. //DDSD_HEIGHT = 0x2,
  77819. //DDSD_WIDTH = 0x4,
  77820. //DDSD_PITCH = 0x8,
  77821. //DDSD_PIXELFORMAT = 0x1000,
  77822. DDSD_MIPMAPCOUNT = 0x20000;
  77823. //DDSD_LINEARSIZE = 0x80000,
  77824. //DDSD_DEPTH = 0x800000;
  77825. // var DDSCAPS_COMPLEX = 0x8,
  77826. // DDSCAPS_MIPMAP = 0x400000,
  77827. // DDSCAPS_TEXTURE = 0x1000;
  77828. var DDSCAPS2_CUBEMAP = 0x200;
  77829. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77830. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77831. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77832. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77833. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77834. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77835. // DDSCAPS2_VOLUME = 0x200000;
  77836. var
  77837. //DDPF_ALPHAPIXELS = 0x1,
  77838. //DDPF_ALPHA = 0x2,
  77839. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77840. //DDPF_YUV = 0x200,
  77841. DDPF_LUMINANCE = 0x20000;
  77842. function FourCCToInt32(value) {
  77843. return value.charCodeAt(0) +
  77844. (value.charCodeAt(1) << 8) +
  77845. (value.charCodeAt(2) << 16) +
  77846. (value.charCodeAt(3) << 24);
  77847. }
  77848. function Int32ToFourCC(value) {
  77849. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77850. }
  77851. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77852. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77853. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77854. var FOURCC_DX10 = FourCCToInt32("DX10");
  77855. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77856. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77857. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77858. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77859. var headerLengthInt = 31; // The header length in 32 bit ints
  77860. // Offsets into the header array
  77861. var off_magic = 0;
  77862. var off_size = 1;
  77863. var off_flags = 2;
  77864. var off_height = 3;
  77865. var off_width = 4;
  77866. var off_mipmapCount = 7;
  77867. var off_pfFlags = 20;
  77868. var off_pfFourCC = 21;
  77869. var off_RGBbpp = 22;
  77870. var off_RMask = 23;
  77871. var off_GMask = 24;
  77872. var off_BMask = 25;
  77873. var off_AMask = 26;
  77874. // var off_caps1 = 27;
  77875. var off_caps2 = 28;
  77876. // var off_caps3 = 29;
  77877. // var off_caps4 = 30;
  77878. var off_dxgiFormat = 32;
  77879. ;
  77880. var DDSTools = /** @class */ (function () {
  77881. function DDSTools() {
  77882. }
  77883. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77884. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77885. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77886. var mipmapCount = 1;
  77887. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77888. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77889. }
  77890. var fourCC = header[off_pfFourCC];
  77891. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77892. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77893. switch (fourCC) {
  77894. case FOURCC_D3DFMT_R16G16B16A16F:
  77895. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77896. break;
  77897. case FOURCC_D3DFMT_R32G32B32A32F:
  77898. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77899. break;
  77900. case FOURCC_DX10:
  77901. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77902. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77903. break;
  77904. }
  77905. }
  77906. return {
  77907. width: header[off_width],
  77908. height: header[off_height],
  77909. mipmapCount: mipmapCount,
  77910. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77911. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77912. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77913. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77914. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77915. dxgiFormat: dxgiFormat,
  77916. textureType: textureType
  77917. };
  77918. };
  77919. DDSTools._ToHalfFloat = function (value) {
  77920. if (!DDSTools._FloatView) {
  77921. DDSTools._FloatView = new Float32Array(1);
  77922. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77923. }
  77924. DDSTools._FloatView[0] = value;
  77925. var x = DDSTools._Int32View[0];
  77926. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77927. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77928. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77929. /* If zero, or denormal, or exponent underflows too much for a denormal
  77930. * half, return signed zero. */
  77931. if (e < 103) {
  77932. return bits;
  77933. }
  77934. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77935. if (e > 142) {
  77936. bits |= 0x7c00;
  77937. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77938. * not Inf, so make sure we set one mantissa bit too. */
  77939. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77940. return bits;
  77941. }
  77942. /* If exponent underflows but not too much, return a denormal */
  77943. if (e < 113) {
  77944. m |= 0x0800;
  77945. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77946. * to 1, which is OK. */
  77947. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77948. return bits;
  77949. }
  77950. bits |= ((e - 112) << 10) | (m >> 1);
  77951. bits += m & 1;
  77952. return bits;
  77953. };
  77954. DDSTools._FromHalfFloat = function (value) {
  77955. var s = (value & 0x8000) >> 15;
  77956. var e = (value & 0x7C00) >> 10;
  77957. var f = value & 0x03FF;
  77958. if (e === 0) {
  77959. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77960. }
  77961. else if (e == 0x1F) {
  77962. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77963. }
  77964. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77965. };
  77966. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77967. var destArray = new Float32Array(dataLength);
  77968. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77969. var index = 0;
  77970. for (var y = 0; y < height; y++) {
  77971. for (var x = 0; x < width; x++) {
  77972. var srcPos = (x + y * width) * 4;
  77973. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77974. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77975. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77976. if (DDSTools.StoreLODInAlphaChannel) {
  77977. destArray[index + 3] = lod;
  77978. }
  77979. else {
  77980. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77981. }
  77982. index += 4;
  77983. }
  77984. }
  77985. return destArray;
  77986. };
  77987. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77988. if (DDSTools.StoreLODInAlphaChannel) {
  77989. var destArray = new Uint16Array(dataLength);
  77990. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77991. var index = 0;
  77992. for (var y = 0; y < height; y++) {
  77993. for (var x = 0; x < width; x++) {
  77994. var srcPos = (x + y * width) * 4;
  77995. destArray[index] = srcData[srcPos];
  77996. destArray[index + 1] = srcData[srcPos + 1];
  77997. destArray[index + 2] = srcData[srcPos + 2];
  77998. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77999. index += 4;
  78000. }
  78001. }
  78002. return destArray;
  78003. }
  78004. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78005. };
  78006. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78007. if (DDSTools.StoreLODInAlphaChannel) {
  78008. var destArray = new Float32Array(dataLength);
  78009. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78010. var index = 0;
  78011. for (var y = 0; y < height; y++) {
  78012. for (var x = 0; x < width; x++) {
  78013. var srcPos = (x + y * width) * 4;
  78014. destArray[index] = srcData[srcPos];
  78015. destArray[index + 1] = srcData[srcPos + 1];
  78016. destArray[index + 2] = srcData[srcPos + 2];
  78017. destArray[index + 3] = lod;
  78018. index += 4;
  78019. }
  78020. }
  78021. return destArray;
  78022. }
  78023. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78024. };
  78025. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78026. var destArray = new Uint8Array(dataLength);
  78027. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78028. var index = 0;
  78029. for (var y = 0; y < height; y++) {
  78030. for (var x = 0; x < width; x++) {
  78031. var srcPos = (x + y * width) * 4;
  78032. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78033. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78034. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78035. if (DDSTools.StoreLODInAlphaChannel) {
  78036. destArray[index + 3] = lod;
  78037. }
  78038. else {
  78039. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78040. }
  78041. index += 4;
  78042. }
  78043. }
  78044. return destArray;
  78045. };
  78046. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78047. var destArray = new Uint8Array(dataLength);
  78048. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78049. var index = 0;
  78050. for (var y = 0; y < height; y++) {
  78051. for (var x = 0; x < width; x++) {
  78052. var srcPos = (x + y * width) * 4;
  78053. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78054. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78055. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78056. if (DDSTools.StoreLODInAlphaChannel) {
  78057. destArray[index + 3] = lod;
  78058. }
  78059. else {
  78060. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78061. }
  78062. index += 4;
  78063. }
  78064. }
  78065. return destArray;
  78066. };
  78067. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78068. var byteArray = new Uint8Array(dataLength);
  78069. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78070. var index = 0;
  78071. for (var y = 0; y < height; y++) {
  78072. for (var x = 0; x < width; x++) {
  78073. var srcPos = (x + y * width) * 4;
  78074. byteArray[index] = srcData[srcPos + rOffset];
  78075. byteArray[index + 1] = srcData[srcPos + gOffset];
  78076. byteArray[index + 2] = srcData[srcPos + bOffset];
  78077. byteArray[index + 3] = srcData[srcPos + aOffset];
  78078. index += 4;
  78079. }
  78080. }
  78081. return byteArray;
  78082. };
  78083. DDSTools._ExtractLongWordOrder = function (value) {
  78084. if (value === 0 || value === 255 || value === -16777216) {
  78085. return 0;
  78086. }
  78087. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78088. };
  78089. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78090. var byteArray = new Uint8Array(dataLength);
  78091. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78092. var index = 0;
  78093. for (var y = 0; y < height; y++) {
  78094. for (var x = 0; x < width; x++) {
  78095. var srcPos = (x + y * width) * 3;
  78096. byteArray[index] = srcData[srcPos + rOffset];
  78097. byteArray[index + 1] = srcData[srcPos + gOffset];
  78098. byteArray[index + 2] = srcData[srcPos + bOffset];
  78099. index += 3;
  78100. }
  78101. }
  78102. return byteArray;
  78103. };
  78104. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78105. var byteArray = new Uint8Array(dataLength);
  78106. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78107. var index = 0;
  78108. for (var y = 0; y < height; y++) {
  78109. for (var x = 0; x < width; x++) {
  78110. var srcPos = (x + y * width);
  78111. byteArray[index] = srcData[srcPos];
  78112. index++;
  78113. }
  78114. }
  78115. return byteArray;
  78116. };
  78117. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78118. if (lodIndex === void 0) { lodIndex = -1; }
  78119. var ext = engine.getCaps().s3tc;
  78120. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78121. var fourCC, width, height, dataLength = 0, dataOffset;
  78122. var byteArray, mipmapCount, mip;
  78123. var internalFormat = 0;
  78124. var format = 0;
  78125. var blockBytes = 1;
  78126. if (header[off_magic] !== DDS_MAGIC) {
  78127. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78128. return;
  78129. }
  78130. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78131. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78132. return;
  78133. }
  78134. if (info.isCompressed && !ext) {
  78135. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78136. return;
  78137. }
  78138. var bpp = header[off_RGBbpp];
  78139. dataOffset = header[off_size] + 4;
  78140. var computeFormats = false;
  78141. if (info.isFourCC) {
  78142. fourCC = header[off_pfFourCC];
  78143. switch (fourCC) {
  78144. case FOURCC_DXT1:
  78145. blockBytes = 8;
  78146. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78147. break;
  78148. case FOURCC_DXT3:
  78149. blockBytes = 16;
  78150. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78151. break;
  78152. case FOURCC_DXT5:
  78153. blockBytes = 16;
  78154. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78155. break;
  78156. case FOURCC_D3DFMT_R16G16B16A16F:
  78157. computeFormats = true;
  78158. break;
  78159. case FOURCC_D3DFMT_R32G32B32A32F:
  78160. computeFormats = true;
  78161. break;
  78162. case FOURCC_DX10:
  78163. // There is an additionnal header so dataOffset need to be changed
  78164. dataOffset += 5 * 4; // 5 uints
  78165. var supported = false;
  78166. switch (info.dxgiFormat) {
  78167. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78168. computeFormats = true;
  78169. supported = true;
  78170. break;
  78171. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78172. info.isRGB = true;
  78173. info.isFourCC = false;
  78174. bpp = 32;
  78175. supported = true;
  78176. break;
  78177. }
  78178. if (supported) {
  78179. break;
  78180. }
  78181. default:
  78182. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78183. return;
  78184. }
  78185. }
  78186. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78187. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78188. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78189. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78190. if (computeFormats) {
  78191. format = engine._getWebGLTextureType(info.textureType);
  78192. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78193. }
  78194. mipmapCount = 1;
  78195. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78196. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78197. }
  78198. for (var face = 0; face < faces; face++) {
  78199. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78200. width = header[off_width];
  78201. height = header[off_height];
  78202. for (mip = 0; mip < mipmapCount; ++mip) {
  78203. if (lodIndex === -1 || lodIndex === mip) {
  78204. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78205. var i = (lodIndex === -1) ? mip : 0;
  78206. if (!info.isCompressed && info.isFourCC) {
  78207. dataLength = width * height * 4;
  78208. var floatArray = null;
  78209. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78210. if (bpp === 128) {
  78211. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78212. }
  78213. else if (bpp === 64) {
  78214. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78215. }
  78216. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78217. format = engine._getWebGLTextureType(info.textureType);
  78218. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78219. }
  78220. else {
  78221. if (bpp === 128) {
  78222. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78223. }
  78224. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78225. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78226. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78227. format = engine._getWebGLTextureType(info.textureType);
  78228. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78229. }
  78230. else {
  78231. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78232. }
  78233. }
  78234. if (floatArray) {
  78235. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78236. }
  78237. }
  78238. else if (info.isRGB) {
  78239. if (bpp === 24) {
  78240. dataLength = width * height * 3;
  78241. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78242. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78243. }
  78244. else {
  78245. dataLength = width * height * 4;
  78246. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78247. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78248. }
  78249. }
  78250. else if (info.isLuminance) {
  78251. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78252. var unpaddedRowSize = width;
  78253. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78254. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78255. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78256. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78257. }
  78258. else {
  78259. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78260. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78261. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78262. }
  78263. }
  78264. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78265. width *= 0.5;
  78266. height *= 0.5;
  78267. width = Math.max(1.0, width);
  78268. height = Math.max(1.0, height);
  78269. }
  78270. if (currentFace !== undefined) {
  78271. // Loading a single face
  78272. break;
  78273. }
  78274. }
  78275. };
  78276. DDSTools.StoreLODInAlphaChannel = false;
  78277. return DDSTools;
  78278. }());
  78279. BABYLON.DDSTools = DDSTools;
  78280. })(BABYLON || (BABYLON = {}));
  78281. //# sourceMappingURL=babylon.dds.js.map
  78282. var BABYLON;
  78283. (function (BABYLON) {
  78284. /**
  78285. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78286. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78287. */
  78288. var KhronosTextureContainer = /** @class */ (function () {
  78289. /**
  78290. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78291. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78292. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78293. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78294. */
  78295. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78296. this.arrayBuffer = arrayBuffer;
  78297. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78298. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78299. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78300. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78301. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78302. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78303. BABYLON.Tools.Error("texture missing KTX identifier");
  78304. return;
  78305. }
  78306. // load the reset of the header in native 32 bit int
  78307. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78308. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78309. var oppositeEndianess = header[0] === 0x01020304;
  78310. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78311. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78312. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78313. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78314. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78315. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78316. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78317. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78318. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78319. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78320. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78321. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78322. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78323. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78324. if (this.glType !== 0) {
  78325. BABYLON.Tools.Error("only compressed formats currently supported");
  78326. return;
  78327. }
  78328. else {
  78329. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78330. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78331. }
  78332. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78333. BABYLON.Tools.Error("only 2D textures currently supported");
  78334. return;
  78335. }
  78336. if (this.numberOfArrayElements !== 0) {
  78337. BABYLON.Tools.Error("texture arrays not currently supported");
  78338. return;
  78339. }
  78340. if (this.numberOfFaces !== facesExpected) {
  78341. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78342. return;
  78343. }
  78344. // we now have a completely validated file, so could use existence of loadType as success
  78345. // would need to make this more elaborate & adjust checks above to support more than one load type
  78346. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78347. }
  78348. // not as fast hardware based, but will probably never need to use
  78349. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78350. return ((val & 0xFF) << 24)
  78351. | ((val & 0xFF00) << 8)
  78352. | ((val >> 8) & 0xFF00)
  78353. | ((val >> 24) & 0xFF);
  78354. };
  78355. /**
  78356. * It is assumed that the texture has already been created & is currently bound
  78357. */
  78358. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78359. switch (this.loadType) {
  78360. case KhronosTextureContainer.COMPRESSED_2D:
  78361. this._upload2DCompressedLevels(gl, loadMipmaps);
  78362. break;
  78363. case KhronosTextureContainer.TEX_2D:
  78364. case KhronosTextureContainer.COMPRESSED_3D:
  78365. case KhronosTextureContainer.TEX_3D:
  78366. }
  78367. };
  78368. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78369. // initialize width & height for level 1
  78370. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78371. var width = this.pixelWidth;
  78372. var height = this.pixelHeight;
  78373. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78374. for (var level = 0; level < mipmapCount; level++) {
  78375. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78376. for (var face = 0; face < this.numberOfFaces; face++) {
  78377. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78378. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78379. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78380. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78381. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78382. }
  78383. width = Math.max(1.0, width * 0.5);
  78384. height = Math.max(1.0, height * 0.5);
  78385. }
  78386. };
  78387. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78388. // load types
  78389. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78390. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78391. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78392. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78393. return KhronosTextureContainer;
  78394. }());
  78395. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78396. })(BABYLON || (BABYLON = {}));
  78397. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78398. var BABYLON;
  78399. (function (BABYLON) {
  78400. var Debug = /** @class */ (function () {
  78401. function Debug() {
  78402. }
  78403. Debug.AxesViewer = /** @class */ (function () {
  78404. function AxesViewer(scene, scaleLines) {
  78405. if (scaleLines === void 0) { scaleLines = 1; }
  78406. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78407. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78408. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78409. this.scaleLines = 1;
  78410. this.scaleLines = scaleLines;
  78411. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78412. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78413. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78414. this._xmesh.renderingGroupId = 2;
  78415. this._ymesh.renderingGroupId = 2;
  78416. this._zmesh.renderingGroupId = 2;
  78417. this._xmesh.material.checkReadyOnlyOnce = true;
  78418. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78419. this._ymesh.material.checkReadyOnlyOnce = true;
  78420. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78421. this._zmesh.material.checkReadyOnlyOnce = true;
  78422. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78423. this.scene = scene;
  78424. }
  78425. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78426. var scaleLines = this.scaleLines;
  78427. if (this._xmesh) {
  78428. this._xmesh.position.copyFrom(position);
  78429. }
  78430. if (this._ymesh) {
  78431. this._ymesh.position.copyFrom(position);
  78432. }
  78433. if (this._zmesh) {
  78434. this._zmesh.position.copyFrom(position);
  78435. }
  78436. var point2 = this._xline[1];
  78437. point2.x = xaxis.x * scaleLines;
  78438. point2.y = xaxis.y * scaleLines;
  78439. point2.z = xaxis.z * scaleLines;
  78440. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78441. point2 = this._yline[1];
  78442. point2.x = yaxis.x * scaleLines;
  78443. point2.y = yaxis.y * scaleLines;
  78444. point2.z = yaxis.z * scaleLines;
  78445. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78446. point2 = this._zline[1];
  78447. point2.x = zaxis.x * scaleLines;
  78448. point2.y = zaxis.y * scaleLines;
  78449. point2.z = zaxis.z * scaleLines;
  78450. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78451. };
  78452. AxesViewer.prototype.dispose = function () {
  78453. if (this._xmesh) {
  78454. this._xmesh.dispose();
  78455. }
  78456. if (this._ymesh) {
  78457. this._ymesh.dispose();
  78458. }
  78459. if (this._zmesh) {
  78460. this._zmesh.dispose();
  78461. }
  78462. this._xmesh = null;
  78463. this._ymesh = null;
  78464. this._zmesh = null;
  78465. this.scene = null;
  78466. };
  78467. return AxesViewer;
  78468. }());
  78469. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78470. __extends(BoneAxesViewer, _super);
  78471. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78472. if (scaleLines === void 0) { scaleLines = 1; }
  78473. var _this = _super.call(this, scene, scaleLines) || this;
  78474. _this.pos = BABYLON.Vector3.Zero();
  78475. _this.xaxis = BABYLON.Vector3.Zero();
  78476. _this.yaxis = BABYLON.Vector3.Zero();
  78477. _this.zaxis = BABYLON.Vector3.Zero();
  78478. _this.mesh = mesh;
  78479. _this.bone = bone;
  78480. return _this;
  78481. }
  78482. BoneAxesViewer.prototype.update = function () {
  78483. if (!this.mesh || !this.bone) {
  78484. return;
  78485. }
  78486. var bone = this.bone;
  78487. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78488. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78489. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78490. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78491. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78492. };
  78493. BoneAxesViewer.prototype.dispose = function () {
  78494. if (this.mesh) {
  78495. this.mesh = null;
  78496. this.bone = null;
  78497. _super.prototype.dispose.call(this);
  78498. }
  78499. };
  78500. return BoneAxesViewer;
  78501. }(Debug.AxesViewer));
  78502. Debug.PhysicsViewer = /** @class */ (function () {
  78503. function PhysicsViewer(scene) {
  78504. this._impostors = [];
  78505. this._meshes = [];
  78506. this._numMeshes = 0;
  78507. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78508. var physicEngine = this._scene.getPhysicsEngine();
  78509. if (physicEngine) {
  78510. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78511. }
  78512. }
  78513. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78514. var plugin = this._physicsEnginePlugin;
  78515. for (var i = 0; i < this._numMeshes; i++) {
  78516. var impostor = this._impostors[i];
  78517. if (!impostor) {
  78518. continue;
  78519. }
  78520. if (impostor.isDisposed) {
  78521. this.hideImpostor(this._impostors[i--]);
  78522. }
  78523. else {
  78524. var mesh = this._meshes[i];
  78525. if (mesh && plugin) {
  78526. plugin.syncMeshWithImpostor(mesh, impostor);
  78527. }
  78528. }
  78529. }
  78530. };
  78531. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78532. if (!this._scene) {
  78533. return;
  78534. }
  78535. for (var i = 0; i < this._numMeshes; i++) {
  78536. if (this._impostors[i] == impostor) {
  78537. return;
  78538. }
  78539. }
  78540. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78541. if (debugMesh) {
  78542. this._impostors[this._numMeshes] = impostor;
  78543. this._meshes[this._numMeshes] = debugMesh;
  78544. if (this._numMeshes === 0) {
  78545. this._renderFunction = this._updateDebugMeshes.bind(this);
  78546. this._scene.registerBeforeRender(this._renderFunction);
  78547. }
  78548. this._numMeshes++;
  78549. }
  78550. };
  78551. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78552. if (!impostor || !this._scene) {
  78553. return;
  78554. }
  78555. var removed = false;
  78556. for (var i = 0; i < this._numMeshes; i++) {
  78557. if (this._impostors[i] == impostor) {
  78558. var mesh = this._meshes[i];
  78559. if (!mesh) {
  78560. continue;
  78561. }
  78562. this._scene.removeMesh(mesh);
  78563. mesh.dispose();
  78564. this._numMeshes--;
  78565. if (this._numMeshes > 0) {
  78566. this._meshes[i] = this._meshes[this._numMeshes];
  78567. this._impostors[i] = this._impostors[this._numMeshes];
  78568. this._meshes[this._numMeshes] = null;
  78569. this._impostors[this._numMeshes] = null;
  78570. }
  78571. else {
  78572. this._meshes[0] = null;
  78573. this._impostors[0] = null;
  78574. }
  78575. removed = true;
  78576. break;
  78577. }
  78578. }
  78579. if (removed && this._numMeshes === 0) {
  78580. this._scene.unregisterBeforeRender(this._renderFunction);
  78581. }
  78582. };
  78583. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78584. if (!this._debugMaterial) {
  78585. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78586. this._debugMaterial.wireframe = true;
  78587. }
  78588. return this._debugMaterial;
  78589. };
  78590. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78591. if (!this._debugBoxMesh) {
  78592. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78593. this._debugBoxMesh.renderingGroupId = 1;
  78594. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78595. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78596. scene.removeMesh(this._debugBoxMesh);
  78597. }
  78598. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78599. };
  78600. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78601. if (!this._debugSphereMesh) {
  78602. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78603. this._debugSphereMesh.renderingGroupId = 1;
  78604. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78605. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78606. scene.removeMesh(this._debugSphereMesh);
  78607. }
  78608. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78609. };
  78610. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78611. var mesh = null;
  78612. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78613. mesh = this._getDebugBoxMesh(scene);
  78614. impostor.getBoxSizeToRef(mesh.scaling);
  78615. }
  78616. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78617. mesh = this._getDebugSphereMesh(scene);
  78618. var radius = impostor.getRadius();
  78619. mesh.scaling.x = radius * 2;
  78620. mesh.scaling.y = radius * 2;
  78621. mesh.scaling.z = radius * 2;
  78622. }
  78623. return mesh;
  78624. };
  78625. PhysicsViewer.prototype.dispose = function () {
  78626. for (var i = 0; i < this._numMeshes; i++) {
  78627. this.hideImpostor(this._impostors[i]);
  78628. }
  78629. if (this._debugBoxMesh) {
  78630. this._debugBoxMesh.dispose();
  78631. }
  78632. if (this._debugSphereMesh) {
  78633. this._debugSphereMesh.dispose();
  78634. }
  78635. if (this._debugMaterial) {
  78636. this._debugMaterial.dispose();
  78637. }
  78638. this._impostors.length = 0;
  78639. this._scene = null;
  78640. this._physicsEnginePlugin = null;
  78641. };
  78642. return PhysicsViewer;
  78643. }());
  78644. Debug.SkeletonViewer = /** @class */ (function () {
  78645. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78646. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78647. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78648. this.skeleton = skeleton;
  78649. this.mesh = mesh;
  78650. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78651. this.renderingGroupId = renderingGroupId;
  78652. this.color = BABYLON.Color3.White();
  78653. this._debugLines = new Array();
  78654. this._isEnabled = false;
  78655. this._scene = scene;
  78656. this.update();
  78657. this._renderFunction = this.update.bind(this);
  78658. }
  78659. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78660. get: function () {
  78661. return this._isEnabled;
  78662. },
  78663. set: function (value) {
  78664. if (this._isEnabled === value) {
  78665. return;
  78666. }
  78667. this._isEnabled = value;
  78668. if (value) {
  78669. this._scene.registerBeforeRender(this._renderFunction);
  78670. }
  78671. else {
  78672. this._scene.unregisterBeforeRender(this._renderFunction);
  78673. }
  78674. },
  78675. enumerable: true,
  78676. configurable: true
  78677. });
  78678. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78679. if (x === void 0) { x = 0; }
  78680. if (y === void 0) { y = 0; }
  78681. if (z === void 0) { z = 0; }
  78682. var tmat = BABYLON.Tmp.Matrix[0];
  78683. var parentBone = bone.getParent();
  78684. tmat.copyFrom(bone.getLocalMatrix());
  78685. if (x !== 0 || y !== 0 || z !== 0) {
  78686. var tmat2 = BABYLON.Tmp.Matrix[1];
  78687. BABYLON.Matrix.IdentityToRef(tmat2);
  78688. tmat2.m[12] = x;
  78689. tmat2.m[13] = y;
  78690. tmat2.m[14] = z;
  78691. tmat2.multiplyToRef(tmat, tmat);
  78692. }
  78693. if (parentBone) {
  78694. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78695. }
  78696. tmat.multiplyToRef(meshMat, tmat);
  78697. position.x = tmat.m[12];
  78698. position.y = tmat.m[13];
  78699. position.z = tmat.m[14];
  78700. };
  78701. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78702. var len = bones.length;
  78703. var meshPos = this.mesh.position;
  78704. for (var i = 0; i < len; i++) {
  78705. var bone = bones[i];
  78706. var points = this._debugLines[i];
  78707. if (!points) {
  78708. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78709. this._debugLines[i] = points;
  78710. }
  78711. this._getBonePosition(points[0], bone, meshMat);
  78712. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78713. points[0].subtractInPlace(meshPos);
  78714. points[1].subtractInPlace(meshPos);
  78715. }
  78716. };
  78717. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78718. var len = bones.length;
  78719. var boneNum = 0;
  78720. var meshPos = this.mesh.position;
  78721. for (var i = len - 1; i >= 0; i--) {
  78722. var childBone = bones[i];
  78723. var parentBone = childBone.getParent();
  78724. if (!parentBone) {
  78725. continue;
  78726. }
  78727. var points = this._debugLines[boneNum];
  78728. if (!points) {
  78729. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78730. this._debugLines[boneNum] = points;
  78731. }
  78732. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78733. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78734. points[0].subtractInPlace(meshPos);
  78735. points[1].subtractInPlace(meshPos);
  78736. boneNum++;
  78737. }
  78738. };
  78739. SkeletonViewer.prototype.update = function () {
  78740. if (this.autoUpdateBonesMatrices) {
  78741. this.skeleton.computeAbsoluteTransforms();
  78742. }
  78743. if (this.skeleton.bones[0].length === undefined) {
  78744. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78745. }
  78746. else {
  78747. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78748. }
  78749. if (!this._debugMesh) {
  78750. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78751. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78752. }
  78753. else {
  78754. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78755. }
  78756. this._debugMesh.position.copyFrom(this.mesh.position);
  78757. this._debugMesh.color = this.color;
  78758. };
  78759. SkeletonViewer.prototype.dispose = function () {
  78760. if (this._debugMesh) {
  78761. this.isEnabled = false;
  78762. this._debugMesh.dispose();
  78763. this._debugMesh = null;
  78764. }
  78765. };
  78766. return SkeletonViewer;
  78767. }());
  78768. return Debug;
  78769. }());
  78770. BABYLON.Debug = Debug;
  78771. })(BABYLON || (BABYLON = {}));
  78772. //# sourceMappingURL=babylon.debugModules.js.map
  78773. var BABYLON;
  78774. (function (BABYLON) {
  78775. var RayHelper = /** @class */ (function () {
  78776. function RayHelper(ray) {
  78777. this.ray = ray;
  78778. }
  78779. RayHelper.CreateAndShow = function (ray, scene, color) {
  78780. var helper = new RayHelper(ray);
  78781. helper.show(scene, color);
  78782. return helper;
  78783. };
  78784. RayHelper.prototype.show = function (scene, color) {
  78785. if (!this._renderFunction && this.ray) {
  78786. var ray = this.ray;
  78787. this._renderFunction = this._render.bind(this);
  78788. this._scene = scene;
  78789. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78790. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78791. if (this._renderFunction) {
  78792. this._scene.registerBeforeRender(this._renderFunction);
  78793. }
  78794. }
  78795. if (color && this._renderLine) {
  78796. this._renderLine.color.copyFrom(color);
  78797. }
  78798. };
  78799. RayHelper.prototype.hide = function () {
  78800. if (this._renderFunction && this._scene) {
  78801. this._scene.unregisterBeforeRender(this._renderFunction);
  78802. this._scene = null;
  78803. this._renderFunction = null;
  78804. if (this._renderLine) {
  78805. this._renderLine.dispose();
  78806. this._renderLine = null;
  78807. }
  78808. this._renderPoints = [];
  78809. }
  78810. };
  78811. RayHelper.prototype._render = function () {
  78812. var ray = this.ray;
  78813. if (!ray) {
  78814. return;
  78815. }
  78816. var point = this._renderPoints[1];
  78817. var len = Math.min(ray.length, 1000000);
  78818. point.copyFrom(ray.direction);
  78819. point.scaleInPlace(len);
  78820. point.addInPlace(ray.origin);
  78821. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78822. };
  78823. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78824. this._attachedToMesh = mesh;
  78825. var ray = this.ray;
  78826. if (!ray) {
  78827. return;
  78828. }
  78829. if (!ray.direction) {
  78830. ray.direction = BABYLON.Vector3.Zero();
  78831. }
  78832. if (!ray.origin) {
  78833. ray.origin = BABYLON.Vector3.Zero();
  78834. }
  78835. if (length) {
  78836. ray.length = length;
  78837. }
  78838. if (!meshSpaceOrigin) {
  78839. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78840. }
  78841. if (!meshSpaceDirection) {
  78842. // -1 so that this will work with Mesh.lookAt
  78843. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78844. }
  78845. if (!this._meshSpaceDirection) {
  78846. this._meshSpaceDirection = meshSpaceDirection.clone();
  78847. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78848. }
  78849. else {
  78850. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78851. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78852. }
  78853. if (!this._updateToMeshFunction) {
  78854. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78855. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78856. }
  78857. this._updateToMesh();
  78858. };
  78859. RayHelper.prototype.detachFromMesh = function () {
  78860. if (this._attachedToMesh) {
  78861. if (this._updateToMeshFunction) {
  78862. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78863. }
  78864. this._attachedToMesh = null;
  78865. this._updateToMeshFunction = null;
  78866. }
  78867. };
  78868. RayHelper.prototype._updateToMesh = function () {
  78869. var ray = this.ray;
  78870. if (!this._attachedToMesh || !ray) {
  78871. return;
  78872. }
  78873. if (this._attachedToMesh._isDisposed) {
  78874. this.detachFromMesh();
  78875. return;
  78876. }
  78877. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78878. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78879. };
  78880. RayHelper.prototype.dispose = function () {
  78881. this.hide();
  78882. this.detachFromMesh();
  78883. this.ray = null;
  78884. };
  78885. return RayHelper;
  78886. }());
  78887. BABYLON.RayHelper = RayHelper;
  78888. })(BABYLON || (BABYLON = {}));
  78889. //# sourceMappingURL=babylon.rayHelper.js.map
  78890. var BABYLON;
  78891. (function (BABYLON) {
  78892. // load the inspector using require, if not present in the global namespace.
  78893. var DebugLayer = /** @class */ (function () {
  78894. function DebugLayer(scene) {
  78895. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78896. this._scene = scene;
  78897. // load inspector using require, if it doesn't exist on the global namespace.
  78898. }
  78899. /** Creates the inspector window. */
  78900. DebugLayer.prototype._createInspector = function (config) {
  78901. if (config === void 0) { config = {}; }
  78902. var popup = config.popup || false;
  78903. var initialTab = config.initialTab || 0;
  78904. var parentElement = config.parentElement || null;
  78905. if (!this._inspector) {
  78906. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78907. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78908. } // else nothing to do,; instance is already existing
  78909. };
  78910. DebugLayer.prototype.isVisible = function () {
  78911. if (!this._inspector) {
  78912. return false;
  78913. }
  78914. return true;
  78915. };
  78916. DebugLayer.prototype.hide = function () {
  78917. if (this._inspector) {
  78918. try {
  78919. this._inspector.dispose();
  78920. }
  78921. catch (e) {
  78922. // If the inspector has been removed directly from the inspector tool
  78923. }
  78924. this._inspector = null;
  78925. }
  78926. };
  78927. DebugLayer.prototype.show = function (config) {
  78928. if (config === void 0) { config = {}; }
  78929. if (typeof this.BJSINSPECTOR == 'undefined') {
  78930. // Load inspector and add it to the DOM
  78931. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78932. }
  78933. else {
  78934. // Otherwise creates the inspector
  78935. this._createInspector(config);
  78936. }
  78937. };
  78938. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78939. return DebugLayer;
  78940. }());
  78941. BABYLON.DebugLayer = DebugLayer;
  78942. })(BABYLON || (BABYLON = {}));
  78943. //# sourceMappingURL=babylon.debugLayer.js.map
  78944. var BABYLON;
  78945. (function (BABYLON) {
  78946. var BoundingBoxRenderer = /** @class */ (function () {
  78947. function BoundingBoxRenderer(scene) {
  78948. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78949. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78950. this.showBackLines = true;
  78951. this.renderList = new BABYLON.SmartArray(32);
  78952. this._vertexBuffers = {};
  78953. this._scene = scene;
  78954. }
  78955. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78956. if (this._colorShader) {
  78957. return;
  78958. }
  78959. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78960. attributes: [BABYLON.VertexBuffer.PositionKind],
  78961. uniforms: ["world", "viewProjection", "color"]
  78962. });
  78963. var engine = this._scene.getEngine();
  78964. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78965. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78966. this._createIndexBuffer();
  78967. };
  78968. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78969. var engine = this._scene.getEngine();
  78970. 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]);
  78971. };
  78972. BoundingBoxRenderer.prototype._rebuild = function () {
  78973. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78974. if (vb) {
  78975. vb._rebuild();
  78976. }
  78977. this._createIndexBuffer();
  78978. };
  78979. BoundingBoxRenderer.prototype.reset = function () {
  78980. this.renderList.reset();
  78981. };
  78982. BoundingBoxRenderer.prototype.render = function () {
  78983. if (this.renderList.length === 0) {
  78984. return;
  78985. }
  78986. this._prepareRessources();
  78987. if (!this._colorShader.isReady()) {
  78988. return;
  78989. }
  78990. var engine = this._scene.getEngine();
  78991. engine.setDepthWrite(false);
  78992. this._colorShader._preBind();
  78993. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78994. var boundingBox = this.renderList.data[boundingBoxIndex];
  78995. var min = boundingBox.minimum;
  78996. var max = boundingBox.maximum;
  78997. var diff = max.subtract(min);
  78998. var median = min.add(diff.scale(0.5));
  78999. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79000. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79001. .multiply(boundingBox.getWorldMatrix());
  79002. // VBOs
  79003. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79004. if (this.showBackLines) {
  79005. // Back
  79006. engine.setDepthFunctionToGreaterOrEqual();
  79007. this._scene.resetCachedMaterial();
  79008. this._colorShader.setColor4("color", this.backColor.toColor4());
  79009. this._colorShader.bind(worldMatrix);
  79010. // Draw order
  79011. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79012. }
  79013. // Front
  79014. engine.setDepthFunctionToLess();
  79015. this._scene.resetCachedMaterial();
  79016. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79017. this._colorShader.bind(worldMatrix);
  79018. // Draw order
  79019. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79020. }
  79021. this._colorShader.unbind();
  79022. engine.setDepthFunctionToLessOrEqual();
  79023. engine.setDepthWrite(true);
  79024. };
  79025. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79026. this._prepareRessources();
  79027. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79028. return;
  79029. }
  79030. var engine = this._scene.getEngine();
  79031. engine.setDepthWrite(false);
  79032. engine.setColorWrite(false);
  79033. this._colorShader._preBind();
  79034. var boundingBox = mesh._boundingInfo.boundingBox;
  79035. var min = boundingBox.minimum;
  79036. var max = boundingBox.maximum;
  79037. var diff = max.subtract(min);
  79038. var median = min.add(diff.scale(0.5));
  79039. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79040. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79041. .multiply(boundingBox.getWorldMatrix());
  79042. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79043. engine.setDepthFunctionToLess();
  79044. this._scene.resetCachedMaterial();
  79045. this._colorShader.bind(worldMatrix);
  79046. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79047. this._colorShader.unbind();
  79048. engine.setDepthFunctionToLessOrEqual();
  79049. engine.setDepthWrite(true);
  79050. engine.setColorWrite(true);
  79051. };
  79052. BoundingBoxRenderer.prototype.dispose = function () {
  79053. if (!this._colorShader) {
  79054. return;
  79055. }
  79056. this.renderList.dispose();
  79057. this._colorShader.dispose();
  79058. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79059. if (buffer) {
  79060. buffer.dispose();
  79061. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79062. }
  79063. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79064. };
  79065. return BoundingBoxRenderer;
  79066. }());
  79067. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79068. })(BABYLON || (BABYLON = {}));
  79069. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79070. var BABYLON;
  79071. (function (BABYLON) {
  79072. var MorphTarget = /** @class */ (function () {
  79073. function MorphTarget(name, influence) {
  79074. if (influence === void 0) { influence = 0; }
  79075. this.name = name;
  79076. this.animations = new Array();
  79077. this._positions = null;
  79078. this._normals = null;
  79079. this._tangents = null;
  79080. this.onInfluenceChanged = new BABYLON.Observable();
  79081. this.influence = influence;
  79082. }
  79083. Object.defineProperty(MorphTarget.prototype, "influence", {
  79084. get: function () {
  79085. return this._influence;
  79086. },
  79087. set: function (influence) {
  79088. if (this._influence === influence) {
  79089. return;
  79090. }
  79091. var previous = this._influence;
  79092. this._influence = influence;
  79093. if (this.onInfluenceChanged.hasObservers) {
  79094. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79095. }
  79096. },
  79097. enumerable: true,
  79098. configurable: true
  79099. });
  79100. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79101. get: function () {
  79102. return !!this._positions;
  79103. },
  79104. enumerable: true,
  79105. configurable: true
  79106. });
  79107. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79108. get: function () {
  79109. return !!this._normals;
  79110. },
  79111. enumerable: true,
  79112. configurable: true
  79113. });
  79114. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79115. get: function () {
  79116. return !!this._tangents;
  79117. },
  79118. enumerable: true,
  79119. configurable: true
  79120. });
  79121. MorphTarget.prototype.setPositions = function (data) {
  79122. this._positions = data;
  79123. };
  79124. MorphTarget.prototype.getPositions = function () {
  79125. return this._positions;
  79126. };
  79127. MorphTarget.prototype.setNormals = function (data) {
  79128. this._normals = data;
  79129. };
  79130. MorphTarget.prototype.getNormals = function () {
  79131. return this._normals;
  79132. };
  79133. MorphTarget.prototype.setTangents = function (data) {
  79134. this._tangents = data;
  79135. };
  79136. MorphTarget.prototype.getTangents = function () {
  79137. return this._tangents;
  79138. };
  79139. /**
  79140. * Serializes the current target into a Serialization object.
  79141. * Returns the serialized object.
  79142. */
  79143. MorphTarget.prototype.serialize = function () {
  79144. var serializationObject = {};
  79145. serializationObject.name = this.name;
  79146. serializationObject.influence = this.influence;
  79147. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79148. if (this.hasNormals) {
  79149. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79150. }
  79151. if (this.hasTangents) {
  79152. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79153. }
  79154. // Animations
  79155. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79156. return serializationObject;
  79157. };
  79158. // Statics
  79159. MorphTarget.Parse = function (serializationObject) {
  79160. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79161. result.setPositions(serializationObject.positions);
  79162. if (serializationObject.normals) {
  79163. result.setNormals(serializationObject.normals);
  79164. }
  79165. if (serializationObject.tangents) {
  79166. result.setTangents(serializationObject.tangents);
  79167. }
  79168. // Animations
  79169. if (serializationObject.animations) {
  79170. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79171. var parsedAnimation = serializationObject.animations[animationIndex];
  79172. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79173. }
  79174. }
  79175. return result;
  79176. };
  79177. MorphTarget.FromMesh = function (mesh, name, influence) {
  79178. if (!name) {
  79179. name = mesh.name;
  79180. }
  79181. var result = new MorphTarget(name, influence);
  79182. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79184. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79185. }
  79186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79187. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79188. }
  79189. return result;
  79190. };
  79191. return MorphTarget;
  79192. }());
  79193. BABYLON.MorphTarget = MorphTarget;
  79194. })(BABYLON || (BABYLON = {}));
  79195. //# sourceMappingURL=babylon.morphTarget.js.map
  79196. var BABYLON;
  79197. (function (BABYLON) {
  79198. var MorphTargetManager = /** @class */ (function () {
  79199. function MorphTargetManager(scene) {
  79200. if (scene === void 0) { scene = null; }
  79201. this._targets = new Array();
  79202. this._targetObservable = new Array();
  79203. this._activeTargets = new BABYLON.SmartArray(16);
  79204. this._supportsNormals = false;
  79205. this._supportsTangents = false;
  79206. this._vertexCount = 0;
  79207. this._uniqueId = 0;
  79208. this._tempInfluences = new Array();
  79209. if (!scene) {
  79210. scene = BABYLON.Engine.LastCreatedScene;
  79211. }
  79212. this._scene = scene;
  79213. if (this._scene) {
  79214. this._scene.morphTargetManagers.push(this);
  79215. this._uniqueId = this._scene.getUniqueId();
  79216. }
  79217. }
  79218. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79219. get: function () {
  79220. return this._uniqueId;
  79221. },
  79222. enumerable: true,
  79223. configurable: true
  79224. });
  79225. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79226. get: function () {
  79227. return this._vertexCount;
  79228. },
  79229. enumerable: true,
  79230. configurable: true
  79231. });
  79232. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79233. get: function () {
  79234. return this._supportsNormals;
  79235. },
  79236. enumerable: true,
  79237. configurable: true
  79238. });
  79239. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79240. get: function () {
  79241. return this._supportsTangents;
  79242. },
  79243. enumerable: true,
  79244. configurable: true
  79245. });
  79246. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79247. get: function () {
  79248. return this._targets.length;
  79249. },
  79250. enumerable: true,
  79251. configurable: true
  79252. });
  79253. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79254. get: function () {
  79255. return this._activeTargets.length;
  79256. },
  79257. enumerable: true,
  79258. configurable: true
  79259. });
  79260. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79261. get: function () {
  79262. return this._influences;
  79263. },
  79264. enumerable: true,
  79265. configurable: true
  79266. });
  79267. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79268. return this._activeTargets.data[index];
  79269. };
  79270. MorphTargetManager.prototype.getTarget = function (index) {
  79271. return this._targets[index];
  79272. };
  79273. MorphTargetManager.prototype.addTarget = function (target) {
  79274. var _this = this;
  79275. this._targets.push(target);
  79276. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79277. _this._syncActiveTargets(needUpdate);
  79278. }));
  79279. this._syncActiveTargets(true);
  79280. };
  79281. MorphTargetManager.prototype.removeTarget = function (target) {
  79282. var index = this._targets.indexOf(target);
  79283. if (index >= 0) {
  79284. this._targets.splice(index, 1);
  79285. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79286. this._syncActiveTargets(true);
  79287. }
  79288. };
  79289. /**
  79290. * Serializes the current manager into a Serialization object.
  79291. * Returns the serialized object.
  79292. */
  79293. MorphTargetManager.prototype.serialize = function () {
  79294. var serializationObject = {};
  79295. serializationObject.id = this.uniqueId;
  79296. serializationObject.targets = [];
  79297. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79298. var target = _a[_i];
  79299. serializationObject.targets.push(target.serialize());
  79300. }
  79301. return serializationObject;
  79302. };
  79303. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79304. var influenceCount = 0;
  79305. this._activeTargets.reset();
  79306. this._supportsNormals = true;
  79307. this._supportsTangents = true;
  79308. this._vertexCount = 0;
  79309. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79310. var target = _a[_i];
  79311. this._activeTargets.push(target);
  79312. this._tempInfluences[influenceCount++] = target.influence;
  79313. var positions = target.getPositions();
  79314. if (positions) {
  79315. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79316. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79317. var vertexCount = positions.length / 3;
  79318. if (this._vertexCount === 0) {
  79319. this._vertexCount = vertexCount;
  79320. }
  79321. else if (this._vertexCount !== vertexCount) {
  79322. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79323. return;
  79324. }
  79325. }
  79326. }
  79327. if (!this._influences || this._influences.length !== influenceCount) {
  79328. this._influences = new Float32Array(influenceCount);
  79329. }
  79330. for (var index = 0; index < influenceCount; index++) {
  79331. this._influences[index] = this._tempInfluences[index];
  79332. }
  79333. if (needUpdate && this._scene) {
  79334. // Flag meshes as dirty to resync with the active targets
  79335. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79336. var mesh = _c[_b];
  79337. if (mesh.morphTargetManager === this) {
  79338. mesh._syncGeometryWithMorphTargetManager();
  79339. }
  79340. }
  79341. }
  79342. };
  79343. // Statics
  79344. MorphTargetManager.Parse = function (serializationObject, scene) {
  79345. var result = new MorphTargetManager(scene);
  79346. result._uniqueId = serializationObject.id;
  79347. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79348. var targetData = _a[_i];
  79349. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79350. }
  79351. return result;
  79352. };
  79353. return MorphTargetManager;
  79354. }());
  79355. BABYLON.MorphTargetManager = MorphTargetManager;
  79356. })(BABYLON || (BABYLON = {}));
  79357. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79358. var BABYLON;
  79359. (function (BABYLON) {
  79360. var Octree = /** @class */ (function () {
  79361. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79362. if (maxDepth === void 0) { maxDepth = 2; }
  79363. this.maxDepth = maxDepth;
  79364. this.dynamicContent = new Array();
  79365. this._maxBlockCapacity = maxBlockCapacity || 64;
  79366. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79367. this._creationFunc = creationFunc;
  79368. }
  79369. // Methods
  79370. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79371. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79372. };
  79373. Octree.prototype.addMesh = function (entry) {
  79374. for (var index = 0; index < this.blocks.length; index++) {
  79375. var block = this.blocks[index];
  79376. block.addEntry(entry);
  79377. }
  79378. };
  79379. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79380. this._selectionContent.reset();
  79381. for (var index = 0; index < this.blocks.length; index++) {
  79382. var block = this.blocks[index];
  79383. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79384. }
  79385. if (allowDuplicate) {
  79386. this._selectionContent.concat(this.dynamicContent);
  79387. }
  79388. else {
  79389. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79390. }
  79391. return this._selectionContent;
  79392. };
  79393. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79394. this._selectionContent.reset();
  79395. for (var index = 0; index < this.blocks.length; index++) {
  79396. var block = this.blocks[index];
  79397. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79398. }
  79399. if (allowDuplicate) {
  79400. this._selectionContent.concat(this.dynamicContent);
  79401. }
  79402. else {
  79403. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79404. }
  79405. return this._selectionContent;
  79406. };
  79407. Octree.prototype.intersectsRay = function (ray) {
  79408. this._selectionContent.reset();
  79409. for (var index = 0; index < this.blocks.length; index++) {
  79410. var block = this.blocks[index];
  79411. block.intersectsRay(ray, this._selectionContent);
  79412. }
  79413. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79414. return this._selectionContent;
  79415. };
  79416. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79417. target.blocks = new Array();
  79418. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79419. // Segmenting space
  79420. for (var x = 0; x < 2; x++) {
  79421. for (var y = 0; y < 2; y++) {
  79422. for (var z = 0; z < 2; z++) {
  79423. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79424. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79425. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79426. block.addEntries(entries);
  79427. target.blocks.push(block);
  79428. }
  79429. }
  79430. }
  79431. };
  79432. Octree.CreationFuncForMeshes = function (entry, block) {
  79433. var boundingInfo = entry.getBoundingInfo();
  79434. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79435. block.entries.push(entry);
  79436. }
  79437. };
  79438. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79439. var boundingInfo = entry.getBoundingInfo();
  79440. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79441. block.entries.push(entry);
  79442. }
  79443. };
  79444. return Octree;
  79445. }());
  79446. BABYLON.Octree = Octree;
  79447. })(BABYLON || (BABYLON = {}));
  79448. //# sourceMappingURL=babylon.octree.js.map
  79449. var BABYLON;
  79450. (function (BABYLON) {
  79451. var OctreeBlock = /** @class */ (function () {
  79452. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79453. this.entries = new Array();
  79454. this._boundingVectors = new Array();
  79455. this._capacity = capacity;
  79456. this._depth = depth;
  79457. this._maxDepth = maxDepth;
  79458. this._creationFunc = creationFunc;
  79459. this._minPoint = minPoint;
  79460. this._maxPoint = maxPoint;
  79461. this._boundingVectors.push(minPoint.clone());
  79462. this._boundingVectors.push(maxPoint.clone());
  79463. this._boundingVectors.push(minPoint.clone());
  79464. this._boundingVectors[2].x = maxPoint.x;
  79465. this._boundingVectors.push(minPoint.clone());
  79466. this._boundingVectors[3].y = maxPoint.y;
  79467. this._boundingVectors.push(minPoint.clone());
  79468. this._boundingVectors[4].z = maxPoint.z;
  79469. this._boundingVectors.push(maxPoint.clone());
  79470. this._boundingVectors[5].z = minPoint.z;
  79471. this._boundingVectors.push(maxPoint.clone());
  79472. this._boundingVectors[6].x = minPoint.x;
  79473. this._boundingVectors.push(maxPoint.clone());
  79474. this._boundingVectors[7].y = minPoint.y;
  79475. }
  79476. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79477. // Property
  79478. get: function () {
  79479. return this._capacity;
  79480. },
  79481. enumerable: true,
  79482. configurable: true
  79483. });
  79484. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79485. get: function () {
  79486. return this._minPoint;
  79487. },
  79488. enumerable: true,
  79489. configurable: true
  79490. });
  79491. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79492. get: function () {
  79493. return this._maxPoint;
  79494. },
  79495. enumerable: true,
  79496. configurable: true
  79497. });
  79498. // Methods
  79499. OctreeBlock.prototype.addEntry = function (entry) {
  79500. if (this.blocks) {
  79501. for (var index = 0; index < this.blocks.length; index++) {
  79502. var block = this.blocks[index];
  79503. block.addEntry(entry);
  79504. }
  79505. return;
  79506. }
  79507. this._creationFunc(entry, this);
  79508. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79509. this.createInnerBlocks();
  79510. }
  79511. };
  79512. OctreeBlock.prototype.addEntries = function (entries) {
  79513. for (var index = 0; index < entries.length; index++) {
  79514. var mesh = entries[index];
  79515. this.addEntry(mesh);
  79516. }
  79517. };
  79518. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79519. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79520. if (this.blocks) {
  79521. for (var index = 0; index < this.blocks.length; index++) {
  79522. var block = this.blocks[index];
  79523. block.select(frustumPlanes, selection, allowDuplicate);
  79524. }
  79525. return;
  79526. }
  79527. if (allowDuplicate) {
  79528. selection.concat(this.entries);
  79529. }
  79530. else {
  79531. selection.concatWithNoDuplicate(this.entries);
  79532. }
  79533. }
  79534. };
  79535. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79536. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79537. if (this.blocks) {
  79538. for (var index = 0; index < this.blocks.length; index++) {
  79539. var block = this.blocks[index];
  79540. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79541. }
  79542. return;
  79543. }
  79544. if (allowDuplicate) {
  79545. selection.concat(this.entries);
  79546. }
  79547. else {
  79548. selection.concatWithNoDuplicate(this.entries);
  79549. }
  79550. }
  79551. };
  79552. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79553. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79554. if (this.blocks) {
  79555. for (var index = 0; index < this.blocks.length; index++) {
  79556. var block = this.blocks[index];
  79557. block.intersectsRay(ray, selection);
  79558. }
  79559. return;
  79560. }
  79561. selection.concatWithNoDuplicate(this.entries);
  79562. }
  79563. };
  79564. OctreeBlock.prototype.createInnerBlocks = function () {
  79565. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79566. };
  79567. return OctreeBlock;
  79568. }());
  79569. BABYLON.OctreeBlock = OctreeBlock;
  79570. })(BABYLON || (BABYLON = {}));
  79571. //# sourceMappingURL=babylon.octreeBlock.js.map
  79572. var BABYLON;
  79573. (function (BABYLON) {
  79574. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79575. __extends(VRDistortionCorrectionPostProcess, _super);
  79576. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79577. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79578. 'LensCenter',
  79579. 'Scale',
  79580. 'ScaleIn',
  79581. 'HmdWarpParam'
  79582. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79583. _this._isRightEye = isRightEye;
  79584. _this._distortionFactors = vrMetrics.distortionK;
  79585. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79586. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79587. _this.adaptScaleToCurrentViewport = true;
  79588. _this.onSizeChangedObservable.add(function () {
  79589. _this.aspectRatio = _this.width * .5 / _this.height;
  79590. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79591. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79592. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79593. });
  79594. _this.onApplyObservable.add(function (effect) {
  79595. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79596. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79597. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79598. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79599. });
  79600. return _this;
  79601. }
  79602. return VRDistortionCorrectionPostProcess;
  79603. }(BABYLON.PostProcess));
  79604. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79605. })(BABYLON || (BABYLON = {}));
  79606. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79607. var BABYLON;
  79608. (function (BABYLON) {
  79609. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79610. __extends(AnaglyphPostProcess, _super);
  79611. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79612. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79613. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79614. _this.onApplyObservable.add(function (effect) {
  79615. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79616. });
  79617. return _this;
  79618. }
  79619. return AnaglyphPostProcess;
  79620. }(BABYLON.PostProcess));
  79621. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79622. })(BABYLON || (BABYLON = {}));
  79623. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79624. var BABYLON;
  79625. (function (BABYLON) {
  79626. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79627. __extends(StereoscopicInterlacePostProcess, _super);
  79628. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79629. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79630. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79631. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79632. _this.onSizeChangedObservable.add(function () {
  79633. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79634. });
  79635. _this.onApplyObservable.add(function (effect) {
  79636. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79637. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79638. });
  79639. return _this;
  79640. }
  79641. return StereoscopicInterlacePostProcess;
  79642. }(BABYLON.PostProcess));
  79643. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79644. })(BABYLON || (BABYLON = {}));
  79645. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79646. var BABYLON;
  79647. (function (BABYLON) {
  79648. /**
  79649. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79650. * Screen rotation is taken into account.
  79651. */
  79652. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79653. function FreeCameraDeviceOrientationInput() {
  79654. var _this = this;
  79655. this._screenOrientationAngle = 0;
  79656. this._screenQuaternion = new BABYLON.Quaternion();
  79657. this._alpha = 0;
  79658. this._beta = 0;
  79659. this._gamma = 0;
  79660. this._orientationChanged = function () {
  79661. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79662. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79663. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79664. };
  79665. this._deviceOrientation = function (evt) {
  79666. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79667. _this._beta = evt.beta !== null ? evt.beta : 0;
  79668. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79669. };
  79670. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79671. this._orientationChanged();
  79672. }
  79673. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79674. get: function () {
  79675. return this._camera;
  79676. },
  79677. set: function (camera) {
  79678. this._camera = camera;
  79679. if (this._camera != null && !this._camera.rotationQuaternion) {
  79680. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79681. }
  79682. },
  79683. enumerable: true,
  79684. configurable: true
  79685. });
  79686. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79687. window.addEventListener("orientationchange", this._orientationChanged);
  79688. window.addEventListener("deviceorientation", this._deviceOrientation);
  79689. //In certain cases, the attach control is called AFTER orientation was changed,
  79690. //So this is needed.
  79691. this._orientationChanged();
  79692. };
  79693. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79694. window.removeEventListener("orientationchange", this._orientationChanged);
  79695. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79696. };
  79697. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79698. //if no device orientation provided, don't update the rotation.
  79699. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79700. if (!this._alpha)
  79701. return;
  79702. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79703. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79704. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79705. //Mirror on XY Plane
  79706. this._camera.rotationQuaternion.z *= -1;
  79707. this._camera.rotationQuaternion.w *= -1;
  79708. };
  79709. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79710. return "FreeCameraDeviceOrientationInput";
  79711. };
  79712. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79713. return "deviceOrientation";
  79714. };
  79715. return FreeCameraDeviceOrientationInput;
  79716. }());
  79717. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79718. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79719. })(BABYLON || (BABYLON = {}));
  79720. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79721. var BABYLON;
  79722. (function (BABYLON) {
  79723. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79724. function ArcRotateCameraVRDeviceOrientationInput() {
  79725. this.alphaCorrection = 1;
  79726. this.betaCorrection = 1;
  79727. this.gammaCorrection = 1;
  79728. this._alpha = 0;
  79729. this._gamma = 0;
  79730. this._dirty = false;
  79731. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79732. }
  79733. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79734. this.camera.attachControl(element, noPreventDefault);
  79735. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79736. };
  79737. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79738. if (evt.alpha !== null) {
  79739. this._alpha = +evt.alpha | 0;
  79740. }
  79741. if (evt.gamma !== null) {
  79742. this._gamma = +evt.gamma | 0;
  79743. }
  79744. this._dirty = true;
  79745. };
  79746. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79747. if (this._dirty) {
  79748. this._dirty = false;
  79749. if (this._gamma < 0) {
  79750. this._gamma = 180 + this._gamma;
  79751. }
  79752. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79753. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79754. }
  79755. };
  79756. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79757. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79758. };
  79759. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79760. return "ArcRotateCameraVRDeviceOrientationInput";
  79761. };
  79762. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79763. return "VRDeviceOrientation";
  79764. };
  79765. return ArcRotateCameraVRDeviceOrientationInput;
  79766. }());
  79767. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79768. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79769. })(BABYLON || (BABYLON = {}));
  79770. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79771. var BABYLON;
  79772. (function (BABYLON) {
  79773. var VRCameraMetrics = /** @class */ (function () {
  79774. function VRCameraMetrics() {
  79775. this.compensateDistortion = true;
  79776. }
  79777. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79778. get: function () {
  79779. return this.hResolution / (2 * this.vResolution);
  79780. },
  79781. enumerable: true,
  79782. configurable: true
  79783. });
  79784. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79785. get: function () {
  79786. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79787. },
  79788. enumerable: true,
  79789. configurable: true
  79790. });
  79791. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79792. get: function () {
  79793. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79794. var h = (4 * meters) / this.hScreenSize;
  79795. return BABYLON.Matrix.Translation(h, 0, 0);
  79796. },
  79797. enumerable: true,
  79798. configurable: true
  79799. });
  79800. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79801. get: function () {
  79802. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79803. var h = (4 * meters) / this.hScreenSize;
  79804. return BABYLON.Matrix.Translation(-h, 0, 0);
  79805. },
  79806. enumerable: true,
  79807. configurable: true
  79808. });
  79809. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79810. get: function () {
  79811. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79812. },
  79813. enumerable: true,
  79814. configurable: true
  79815. });
  79816. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79817. get: function () {
  79818. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79819. },
  79820. enumerable: true,
  79821. configurable: true
  79822. });
  79823. VRCameraMetrics.GetDefault = function () {
  79824. var result = new VRCameraMetrics();
  79825. result.hResolution = 1280;
  79826. result.vResolution = 800;
  79827. result.hScreenSize = 0.149759993;
  79828. result.vScreenSize = 0.0935999975;
  79829. result.vScreenCenter = 0.0467999987;
  79830. result.eyeToScreenDistance = 0.0410000011;
  79831. result.lensSeparationDistance = 0.0635000020;
  79832. result.interpupillaryDistance = 0.0640000030;
  79833. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79834. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79835. result.postProcessScaleFactor = 1.714605507808412;
  79836. result.lensCenterOffset = 0.151976421;
  79837. return result;
  79838. };
  79839. return VRCameraMetrics;
  79840. }());
  79841. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79842. })(BABYLON || (BABYLON = {}));
  79843. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79844. var BABYLON;
  79845. (function (BABYLON) {
  79846. /**
  79847. * This represents a WebVR camera.
  79848. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79849. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79850. */
  79851. var WebVRFreeCamera = /** @class */ (function (_super) {
  79852. __extends(WebVRFreeCamera, _super);
  79853. /**
  79854. * Instantiates a WebVRFreeCamera.
  79855. * @param name The name of the WebVRFreeCamera
  79856. * @param position The starting anchor position for the camera
  79857. * @param scene The scene the camera belongs to
  79858. * @param webVROptions a set of customizable options for the webVRCamera
  79859. */
  79860. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79861. if (webVROptions === void 0) { webVROptions = {}; }
  79862. var _this = _super.call(this, name, position, scene) || this;
  79863. _this.webVROptions = webVROptions;
  79864. /**
  79865. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79866. */
  79867. _this._vrDevice = null;
  79868. /**
  79869. * The rawPose of the vrDevice.
  79870. */
  79871. _this.rawPose = null;
  79872. _this._specsVersion = "1.1";
  79873. _this._attached = false;
  79874. _this._descendants = [];
  79875. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79876. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79877. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79878. _this._standingMatrix = null;
  79879. /**
  79880. * Represents device position in babylon space.
  79881. */
  79882. _this.devicePosition = BABYLON.Vector3.Zero();
  79883. /**
  79884. * Represents device rotation in babylon space.
  79885. */
  79886. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79887. /**
  79888. * The scale of the device to be used when translating from device space to babylon space.
  79889. */
  79890. _this.deviceScaleFactor = 1;
  79891. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79892. _this._worldToDevice = BABYLON.Matrix.Identity();
  79893. /**
  79894. * References to the webVR controllers for the vrDevice.
  79895. */
  79896. _this.controllers = [];
  79897. /**
  79898. * Emits an event when a controller is attached.
  79899. */
  79900. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79901. /**
  79902. * Emits an event when a controller's mesh has been loaded;
  79903. */
  79904. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79905. /**
  79906. * If the rig cameras be used as parent instead of this camera.
  79907. */
  79908. _this.rigParenting = true;
  79909. _this._defaultHeight = undefined;
  79910. _this._workingVector = BABYLON.Vector3.Zero();
  79911. _this._oneVector = BABYLON.Vector3.One();
  79912. _this._workingMatrix = BABYLON.Matrix.Identity();
  79913. _this._cache.position = BABYLON.Vector3.Zero();
  79914. if (webVROptions.defaultHeight) {
  79915. _this._defaultHeight = webVROptions.defaultHeight;
  79916. _this.position.y = _this._defaultHeight;
  79917. }
  79918. _this.minZ = 0.1;
  79919. //legacy support - the compensation boolean was removed.
  79920. if (arguments.length === 5) {
  79921. _this.webVROptions = arguments[4];
  79922. }
  79923. // default webVR options
  79924. if (_this.webVROptions.trackPosition == undefined) {
  79925. _this.webVROptions.trackPosition = true;
  79926. }
  79927. if (_this.webVROptions.controllerMeshes == undefined) {
  79928. _this.webVROptions.controllerMeshes = true;
  79929. }
  79930. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79931. _this.webVROptions.defaultLightingOnControllers = true;
  79932. }
  79933. _this.rotationQuaternion = new BABYLON.Quaternion();
  79934. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79935. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79936. }
  79937. //enable VR
  79938. var engine = _this.getEngine();
  79939. _this._onVREnabled = function (success) { if (success) {
  79940. _this.initControllers();
  79941. } };
  79942. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79943. engine.initWebVR().add(function (event) {
  79944. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79945. return;
  79946. }
  79947. _this._vrDevice = event.vrDisplay;
  79948. //reset the rig parameters.
  79949. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79950. if (_this._attached) {
  79951. _this.getEngine().enableVR();
  79952. }
  79953. });
  79954. if (typeof (VRFrameData) !== "undefined")
  79955. _this._frameData = new VRFrameData();
  79956. /**
  79957. * The idea behind the following lines:
  79958. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79959. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79960. * the second will not show it correctly.
  79961. *
  79962. * To solve this - each object that has the camera as parent will be added to a protected array.
  79963. * When the rig camera renders, it will take this array and set all of those to be its children.
  79964. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79965. * Amazing!
  79966. */
  79967. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79968. if (camera.parent === _this && _this.rigParenting) {
  79969. _this._descendants = _this.getDescendants(true, function (n) {
  79970. // don't take the cameras or the controllers!
  79971. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79972. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79973. return !isController && !isRigCamera;
  79974. });
  79975. _this._descendants.forEach(function (node) {
  79976. node.parent = camera;
  79977. });
  79978. }
  79979. });
  79980. scene.onAfterCameraRenderObservable.add(function (camera) {
  79981. if (camera.parent === _this && _this.rigParenting) {
  79982. _this._descendants.forEach(function (node) {
  79983. node.parent = _this;
  79984. });
  79985. }
  79986. });
  79987. return _this;
  79988. }
  79989. /**
  79990. * Gets the device distance from the ground in meters.
  79991. * @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.
  79992. */
  79993. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79994. if (this._standingMatrix) {
  79995. // Add standing matrix offset to get real offset from ground in room
  79996. this._standingMatrix.getTranslationToRef(this._workingVector);
  79997. return this._deviceRoomPosition.y + this._workingVector.y;
  79998. }
  79999. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80000. return this._defaultHeight || 0;
  80001. };
  80002. /**
  80003. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80004. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80005. */
  80006. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80007. var _this = this;
  80008. if (callback === void 0) { callback = function (bool) { }; }
  80009. // Use standing matrix if available
  80010. this.getEngine().initWebVRAsync().then(function (result) {
  80011. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80012. callback(false);
  80013. }
  80014. else {
  80015. _this._standingMatrix = new BABYLON.Matrix();
  80016. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80017. if (!_this.getScene().useRightHandedSystem) {
  80018. [2, 6, 8, 9, 14].forEach(function (num) {
  80019. if (_this._standingMatrix) {
  80020. _this._standingMatrix.m[num] *= -1;
  80021. }
  80022. });
  80023. }
  80024. callback(true);
  80025. }
  80026. });
  80027. };
  80028. /**
  80029. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80030. * @returns A promise with a boolean set to if the standing matrix is supported.
  80031. */
  80032. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80033. var _this = this;
  80034. return new Promise(function (res, rej) {
  80035. _this.useStandingMatrix(function (supported) {
  80036. res(supported);
  80037. });
  80038. });
  80039. };
  80040. /**
  80041. * Disposes the camera
  80042. */
  80043. WebVRFreeCamera.prototype.dispose = function () {
  80044. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80045. _super.prototype.dispose.call(this);
  80046. };
  80047. /**
  80048. * Gets a vrController by name.
  80049. * @param name The name of the controller to retreive
  80050. * @returns the controller matching the name specified or null if not found
  80051. */
  80052. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80053. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80054. var gp = _a[_i];
  80055. if (gp.hand === name) {
  80056. return gp;
  80057. }
  80058. }
  80059. return null;
  80060. };
  80061. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80062. /**
  80063. * The controller corrisponding to the users left hand.
  80064. */
  80065. get: function () {
  80066. if (!this._leftController) {
  80067. this._leftController = this.getControllerByName("left");
  80068. }
  80069. return this._leftController;
  80070. },
  80071. enumerable: true,
  80072. configurable: true
  80073. });
  80074. ;
  80075. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80076. /**
  80077. * The controller corrisponding to the users right hand.
  80078. */
  80079. get: function () {
  80080. if (!this._rightController) {
  80081. this._rightController = this.getControllerByName("right");
  80082. }
  80083. return this._rightController;
  80084. },
  80085. enumerable: true,
  80086. configurable: true
  80087. });
  80088. ;
  80089. /**
  80090. * Casts a ray forward from the vrCamera's gaze.
  80091. * @param length Length of the ray (default: 100)
  80092. * @returns the ray corrisponding to the gaze
  80093. */
  80094. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80095. if (length === void 0) { length = 100; }
  80096. if (this.leftCamera) {
  80097. // Use left eye to avoid computation to compute center on every call
  80098. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80099. }
  80100. else {
  80101. return _super.prototype.getForwardRay.call(this, length);
  80102. }
  80103. };
  80104. /**
  80105. * Updates the camera based on device's frame data
  80106. */
  80107. WebVRFreeCamera.prototype._checkInputs = function () {
  80108. if (this._vrDevice && this._vrDevice.isPresenting) {
  80109. this._vrDevice.getFrameData(this._frameData);
  80110. this.updateFromDevice(this._frameData.pose);
  80111. }
  80112. _super.prototype._checkInputs.call(this);
  80113. };
  80114. /**
  80115. * Updates the poseControlled values based on the input device pose.
  80116. * @param poseData Pose coming from the device
  80117. */
  80118. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80119. if (poseData && poseData.orientation) {
  80120. this.rawPose = poseData;
  80121. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80122. if (this.getScene().useRightHandedSystem) {
  80123. this._deviceRoomRotationQuaternion.z *= -1;
  80124. this._deviceRoomRotationQuaternion.w *= -1;
  80125. }
  80126. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80127. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80128. if (this.getScene().useRightHandedSystem) {
  80129. this._deviceRoomPosition.z *= -1;
  80130. }
  80131. }
  80132. }
  80133. };
  80134. /**
  80135. * WebVR's attach control will start broadcasting frames to the device.
  80136. * Note that in certain browsers (chrome for example) this function must be called
  80137. * within a user-interaction callback. Example:
  80138. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80139. *
  80140. * @param element html element to attach the vrDevice to
  80141. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80142. */
  80143. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80144. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80145. this._attached = true;
  80146. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80147. if (this._vrDevice) {
  80148. this.getEngine().enableVR();
  80149. }
  80150. };
  80151. /**
  80152. * Detaches the camera from the html element and disables VR
  80153. *
  80154. * @param element html element to detach from
  80155. */
  80156. WebVRFreeCamera.prototype.detachControl = function (element) {
  80157. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80158. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80159. _super.prototype.detachControl.call(this, element);
  80160. this._attached = false;
  80161. this.getEngine().disableVR();
  80162. };
  80163. /**
  80164. * @returns the name of this class
  80165. */
  80166. WebVRFreeCamera.prototype.getClassName = function () {
  80167. return "WebVRFreeCamera";
  80168. };
  80169. /**
  80170. * Calls resetPose on the vrDisplay
  80171. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80172. */
  80173. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80174. //uses the vrDisplay's "resetPose()".
  80175. //pitch and roll won't be affected.
  80176. this._vrDevice.resetPose();
  80177. };
  80178. /**
  80179. * Updates the rig cameras (left and right eye)
  80180. */
  80181. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80182. var camLeft = this._rigCameras[0];
  80183. var camRight = this._rigCameras[1];
  80184. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80185. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80186. camLeft.position.copyFrom(this._deviceRoomPosition);
  80187. camRight.position.copyFrom(this._deviceRoomPosition);
  80188. };
  80189. /**
  80190. * Updates the cached values of the camera
  80191. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80192. */
  80193. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80194. var _this = this;
  80195. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80196. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80197. if (!this.updateCacheCalled) {
  80198. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80199. this.updateCacheCalled = true;
  80200. this.update();
  80201. }
  80202. // Set working vector to the device position in room space rotated by the new rotation
  80203. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80204. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80205. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80206. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80207. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80208. // Add translation from anchor position
  80209. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80210. this._workingVector.addInPlace(this.position);
  80211. this._workingVector.subtractInPlace(this._cache.position);
  80212. this._deviceToWorld.setTranslation(this._workingVector);
  80213. // Set an inverted matrix to be used when updating the camera
  80214. this._deviceToWorld.invertToRef(this._worldToDevice);
  80215. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80216. this.controllers.forEach(function (controller) {
  80217. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80218. controller.update();
  80219. });
  80220. }
  80221. if (!ignoreParentClass) {
  80222. _super.prototype._updateCache.call(this);
  80223. }
  80224. this.updateCacheCalled = false;
  80225. };
  80226. /**
  80227. * Updates the current device position and rotation in the babylon world
  80228. */
  80229. WebVRFreeCamera.prototype.update = function () {
  80230. // Get current device position in babylon world
  80231. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80232. // Get current device rotation in babylon world
  80233. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80234. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80235. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80236. _super.prototype.update.call(this);
  80237. };
  80238. /**
  80239. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80240. * @returns an identity matrix
  80241. */
  80242. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80243. return BABYLON.Matrix.Identity();
  80244. };
  80245. /**
  80246. * This function is called by the two RIG cameras.
  80247. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80248. */
  80249. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80250. var _this = this;
  80251. // Update the parent camera prior to using a child camera to avoid desynchronization
  80252. var parentCamera = this._cameraRigParams["parentCamera"];
  80253. parentCamera._updateCache();
  80254. //WebVR 1.1
  80255. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80256. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80257. if (!this.getScene().useRightHandedSystem) {
  80258. [2, 6, 8, 9, 14].forEach(function (num) {
  80259. _this._webvrViewMatrix.m[num] *= -1;
  80260. });
  80261. }
  80262. // update the camera rotation matrix
  80263. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80264. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80265. // Computing target and final matrix
  80266. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80267. // should the view matrix be updated with scale and position offset?
  80268. if (parentCamera.deviceScaleFactor !== 1) {
  80269. this._webvrViewMatrix.invert();
  80270. // scale the position, if set
  80271. if (parentCamera.deviceScaleFactor) {
  80272. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80273. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80274. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80275. }
  80276. this._webvrViewMatrix.invert();
  80277. }
  80278. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80279. return this._webvrViewMatrix;
  80280. };
  80281. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80282. var _this = this;
  80283. var parentCamera = this.parent;
  80284. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80285. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80286. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80287. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80288. //babylon compatible matrix
  80289. if (!this.getScene().useRightHandedSystem) {
  80290. [8, 9, 10, 11].forEach(function (num) {
  80291. _this._projectionMatrix.m[num] *= -1;
  80292. });
  80293. }
  80294. return this._projectionMatrix;
  80295. };
  80296. /**
  80297. * Initializes the controllers and their meshes
  80298. */
  80299. WebVRFreeCamera.prototype.initControllers = function () {
  80300. var _this = this;
  80301. this.controllers = [];
  80302. var manager = this.getScene().gamepadManager;
  80303. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80304. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80305. var webVrController = gamepad;
  80306. if (webVrController.defaultModel) {
  80307. webVrController.defaultModel.setEnabled(false);
  80308. }
  80309. if (webVrController.hand === "right") {
  80310. _this._rightController = null;
  80311. }
  80312. if (webVrController.hand === "left") {
  80313. _this._leftController = null;
  80314. }
  80315. var controllerIndex = _this.controllers.indexOf(webVrController);
  80316. if (controllerIndex !== -1) {
  80317. _this.controllers.splice(controllerIndex, 1);
  80318. }
  80319. }
  80320. });
  80321. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80322. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80323. var webVrController_1 = gamepad;
  80324. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80325. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80326. if (_this.webVROptions.controllerMeshes) {
  80327. if (webVrController_1.defaultModel) {
  80328. webVrController_1.defaultModel.setEnabled(true);
  80329. }
  80330. else {
  80331. // Load the meshes
  80332. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80333. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80334. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80335. if (_this.webVROptions.defaultLightingOnControllers) {
  80336. if (!_this._lightOnControllers) {
  80337. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80338. }
  80339. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80340. var children = mesh.getChildren();
  80341. if (children.length !== 0) {
  80342. children.forEach(function (mesh) {
  80343. light.includedOnlyMeshes.push(mesh);
  80344. activateLightOnSubMeshes_1(mesh, light);
  80345. });
  80346. }
  80347. };
  80348. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80349. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80350. }
  80351. });
  80352. }
  80353. }
  80354. webVrController_1.attachToPoseControlledCamera(_this);
  80355. // since this is async - sanity check. Is the controller already stored?
  80356. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80357. //add to the controllers array
  80358. _this.controllers.push(webVrController_1);
  80359. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80360. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80361. // So we're overriding setting left & right manually to be sure
  80362. var firstViveWandDetected = false;
  80363. for (var i = 0; i < _this.controllers.length; i++) {
  80364. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80365. if (!firstViveWandDetected) {
  80366. firstViveWandDetected = true;
  80367. _this.controllers[i].hand = "left";
  80368. }
  80369. else {
  80370. _this.controllers[i].hand = "right";
  80371. }
  80372. }
  80373. }
  80374. //did we find enough controllers? Great! let the developer know.
  80375. if (_this.controllers.length >= 2) {
  80376. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80377. }
  80378. }
  80379. }
  80380. });
  80381. };
  80382. return WebVRFreeCamera;
  80383. }(BABYLON.FreeCamera));
  80384. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80385. })(BABYLON || (BABYLON = {}));
  80386. //# sourceMappingURL=babylon.webVRCamera.js.map
  80387. var BABYLON;
  80388. (function (BABYLON) {
  80389. // We're mainly based on the logic defined into the FreeCamera code
  80390. /**
  80391. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80392. * being tilted forward or back and left or right.
  80393. */
  80394. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80395. __extends(DeviceOrientationCamera, _super);
  80396. /**
  80397. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80398. * @param name The name of the camera
  80399. * @param position The start position camera
  80400. * @param scene The scene the camera belongs to
  80401. */
  80402. function DeviceOrientationCamera(name, position, scene) {
  80403. var _this = _super.call(this, name, position, scene) || this;
  80404. _this._quaternionCache = new BABYLON.Quaternion();
  80405. _this.inputs.addDeviceOrientation();
  80406. return _this;
  80407. }
  80408. /**
  80409. * Gets the current instance class name ("DeviceOrientationCamera").
  80410. * This helps avoiding instanceof at run time.
  80411. * @returns the class name
  80412. */
  80413. DeviceOrientationCamera.prototype.getClassName = function () {
  80414. return "DeviceOrientationCamera";
  80415. };
  80416. /**
  80417. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80418. */
  80419. DeviceOrientationCamera.prototype._checkInputs = function () {
  80420. _super.prototype._checkInputs.call(this);
  80421. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80422. if (this._initialQuaternion) {
  80423. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80424. }
  80425. };
  80426. /**
  80427. * Reset the camera to its default orientation on the specified axis only.
  80428. * @param axis The axis to reset
  80429. */
  80430. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80431. var _this = this;
  80432. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80433. //can only work if this camera has a rotation quaternion already.
  80434. if (!this.rotationQuaternion)
  80435. return;
  80436. if (!this._initialQuaternion) {
  80437. this._initialQuaternion = new BABYLON.Quaternion();
  80438. }
  80439. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80440. ['x', 'y', 'z'].forEach(function (axisName) {
  80441. if (!axis[axisName]) {
  80442. _this._initialQuaternion[axisName] = 0;
  80443. }
  80444. else {
  80445. _this._initialQuaternion[axisName] *= -1;
  80446. }
  80447. });
  80448. this._initialQuaternion.normalize();
  80449. //force rotation update
  80450. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80451. };
  80452. return DeviceOrientationCamera;
  80453. }(BABYLON.FreeCamera));
  80454. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80455. })(BABYLON || (BABYLON = {}));
  80456. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80457. var BABYLON;
  80458. (function (BABYLON) {
  80459. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80460. __extends(VRDeviceOrientationFreeCamera, _super);
  80461. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80462. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80463. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80464. var _this = _super.call(this, name, position, scene) || this;
  80465. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80466. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80467. return _this;
  80468. }
  80469. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80470. return "VRDeviceOrientationFreeCamera";
  80471. };
  80472. return VRDeviceOrientationFreeCamera;
  80473. }(BABYLON.DeviceOrientationCamera));
  80474. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80475. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80476. __extends(VRDeviceOrientationGamepadCamera, _super);
  80477. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80478. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80479. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80480. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80481. _this.inputs.addGamepad();
  80482. return _this;
  80483. }
  80484. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80485. return "VRDeviceOrientationGamepadCamera";
  80486. };
  80487. return VRDeviceOrientationGamepadCamera;
  80488. }(VRDeviceOrientationFreeCamera));
  80489. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80490. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80491. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80492. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80493. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80494. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80495. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80496. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80497. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80498. _this.inputs.addVRDeviceOrientation();
  80499. return _this;
  80500. }
  80501. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80502. return "VRDeviceOrientationArcRotateCamera";
  80503. };
  80504. return VRDeviceOrientationArcRotateCamera;
  80505. }(BABYLON.ArcRotateCamera));
  80506. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80507. })(BABYLON || (BABYLON = {}));
  80508. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80509. var BABYLON;
  80510. (function (BABYLON) {
  80511. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80512. __extends(AnaglyphFreeCamera, _super);
  80513. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80514. var _this = _super.call(this, name, position, scene) || this;
  80515. _this.interaxialDistance = interaxialDistance;
  80516. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80517. return _this;
  80518. }
  80519. AnaglyphFreeCamera.prototype.getClassName = function () {
  80520. return "AnaglyphFreeCamera";
  80521. };
  80522. return AnaglyphFreeCamera;
  80523. }(BABYLON.FreeCamera));
  80524. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80525. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80526. __extends(AnaglyphArcRotateCamera, _super);
  80527. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80528. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80529. _this.interaxialDistance = interaxialDistance;
  80530. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80531. return _this;
  80532. }
  80533. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80534. return "AnaglyphArcRotateCamera";
  80535. };
  80536. return AnaglyphArcRotateCamera;
  80537. }(BABYLON.ArcRotateCamera));
  80538. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80539. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80540. __extends(AnaglyphGamepadCamera, _super);
  80541. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80542. var _this = _super.call(this, name, position, scene) || this;
  80543. _this.interaxialDistance = interaxialDistance;
  80544. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80545. return _this;
  80546. }
  80547. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80548. return "AnaglyphGamepadCamera";
  80549. };
  80550. return AnaglyphGamepadCamera;
  80551. }(BABYLON.GamepadCamera));
  80552. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80553. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80554. __extends(AnaglyphUniversalCamera, _super);
  80555. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80556. var _this = _super.call(this, name, position, scene) || this;
  80557. _this.interaxialDistance = interaxialDistance;
  80558. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80559. return _this;
  80560. }
  80561. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80562. return "AnaglyphUniversalCamera";
  80563. };
  80564. return AnaglyphUniversalCamera;
  80565. }(BABYLON.UniversalCamera));
  80566. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80567. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80568. __extends(StereoscopicFreeCamera, _super);
  80569. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80570. var _this = _super.call(this, name, position, scene) || this;
  80571. _this.interaxialDistance = interaxialDistance;
  80572. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80573. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80574. return _this;
  80575. }
  80576. StereoscopicFreeCamera.prototype.getClassName = function () {
  80577. return "StereoscopicFreeCamera";
  80578. };
  80579. return StereoscopicFreeCamera;
  80580. }(BABYLON.FreeCamera));
  80581. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80582. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80583. __extends(StereoscopicArcRotateCamera, _super);
  80584. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80585. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80586. _this.interaxialDistance = interaxialDistance;
  80587. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80588. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80589. return _this;
  80590. }
  80591. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80592. return "StereoscopicArcRotateCamera";
  80593. };
  80594. return StereoscopicArcRotateCamera;
  80595. }(BABYLON.ArcRotateCamera));
  80596. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80597. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80598. __extends(StereoscopicGamepadCamera, _super);
  80599. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80600. var _this = _super.call(this, name, position, scene) || this;
  80601. _this.interaxialDistance = interaxialDistance;
  80602. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80603. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80604. return _this;
  80605. }
  80606. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80607. return "StereoscopicGamepadCamera";
  80608. };
  80609. return StereoscopicGamepadCamera;
  80610. }(BABYLON.GamepadCamera));
  80611. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80612. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80613. __extends(StereoscopicUniversalCamera, _super);
  80614. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80615. var _this = _super.call(this, name, position, scene) || this;
  80616. _this.interaxialDistance = interaxialDistance;
  80617. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80618. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80619. return _this;
  80620. }
  80621. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80622. return "StereoscopicUniversalCamera";
  80623. };
  80624. return StereoscopicUniversalCamera;
  80625. }(BABYLON.UniversalCamera));
  80626. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80627. })(BABYLON || (BABYLON = {}));
  80628. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80629. var BABYLON;
  80630. (function (BABYLON) {
  80631. var VRExperienceHelperGazer = /** @class */ (function () {
  80632. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80633. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80634. this.scene = scene;
  80635. this._pointerDownOnMeshAsked = false;
  80636. this._isActionableMesh = false;
  80637. this._teleportationRequestInitiated = false;
  80638. this._teleportationBackRequestInitiated = false;
  80639. this._dpadPressed = true;
  80640. this._activePointer = false;
  80641. this._id = VRExperienceHelperGazer._idCounter++;
  80642. // Gaze tracker
  80643. if (!gazeTrackerToClone) {
  80644. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80645. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80646. this._gazeTracker.isPickable = false;
  80647. this._gazeTracker.isVisible = false;
  80648. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80649. targetMat.specularColor = BABYLON.Color3.Black();
  80650. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80651. targetMat.backFaceCulling = false;
  80652. this._gazeTracker.material = targetMat;
  80653. }
  80654. else {
  80655. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80656. }
  80657. }
  80658. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80659. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80660. };
  80661. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80662. this._pointerDownOnMeshAsked = true;
  80663. if (this._currentMeshSelected && this._currentHit) {
  80664. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80665. }
  80666. };
  80667. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80668. if (this._currentMeshSelected && this._currentHit) {
  80669. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80670. }
  80671. this._pointerDownOnMeshAsked = false;
  80672. };
  80673. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80674. this._activePointer = true;
  80675. };
  80676. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80677. this._activePointer = false;
  80678. };
  80679. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80680. };
  80681. VRExperienceHelperGazer.prototype.dispose = function () {
  80682. this._interactionsEnabled = false;
  80683. this._teleportationEnabled = false;
  80684. };
  80685. VRExperienceHelperGazer._idCounter = 0;
  80686. return VRExperienceHelperGazer;
  80687. }());
  80688. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80689. __extends(VRExperienceHelperControllerGazer, _super);
  80690. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80691. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80692. _this.webVRController = webVRController;
  80693. // Laser pointer
  80694. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80695. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80696. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80697. laserPointerMaterial.alpha = 0.6;
  80698. _this._laserPointer.material = laserPointerMaterial;
  80699. _this._laserPointer.rotation.x = Math.PI / 2;
  80700. _this._laserPointer.position.z = -0.5;
  80701. _this._laserPointer.isVisible = false;
  80702. if (!webVRController.mesh) {
  80703. // Create an empty mesh that is used prior to loading the high quality model
  80704. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80705. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80706. preloadPointerPose.rotation.x = -0.7;
  80707. preloadMesh.addChild(preloadPointerPose);
  80708. webVRController.attachToMesh(preloadMesh);
  80709. }
  80710. _this._setLaserPointerParent(webVRController.mesh);
  80711. return _this;
  80712. }
  80713. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80714. return this.webVRController.getForwardRay(length);
  80715. };
  80716. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80717. _super.prototype._activatePointer.call(this);
  80718. this._laserPointer.isVisible = true;
  80719. };
  80720. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80721. _super.prototype._deactivatePointer.call(this);
  80722. this._laserPointer.isVisible = false;
  80723. };
  80724. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80725. this._laserPointer.material.emissiveColor = color;
  80726. };
  80727. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80728. var makeNotPick = function (root) {
  80729. root.name += " laserPointer";
  80730. root.getChildMeshes().forEach(function (c) {
  80731. makeNotPick(c);
  80732. });
  80733. };
  80734. makeNotPick(mesh);
  80735. var childMeshes = mesh.getChildMeshes();
  80736. this.webVRController._pointingPoseNode = null;
  80737. for (var i = 0; i < childMeshes.length; i++) {
  80738. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80739. mesh = childMeshes[i];
  80740. this.webVRController._pointingPoseNode = mesh;
  80741. break;
  80742. }
  80743. }
  80744. this._laserPointer.parent = mesh;
  80745. };
  80746. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80747. this._laserPointer.scaling.y = distance;
  80748. this._laserPointer.position.z = -distance / 2;
  80749. };
  80750. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80751. _super.prototype.dispose.call(this);
  80752. this._laserPointer.dispose();
  80753. };
  80754. return VRExperienceHelperControllerGazer;
  80755. }(VRExperienceHelperGazer));
  80756. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80757. __extends(VRExperienceHelperCameraGazer, _super);
  80758. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80759. var _this = _super.call(this, scene) || this;
  80760. _this.getCamera = getCamera;
  80761. return _this;
  80762. }
  80763. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80764. var camera = this.getCamera();
  80765. if (camera) {
  80766. return camera.getForwardRay(length);
  80767. }
  80768. else {
  80769. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80770. }
  80771. };
  80772. return VRExperienceHelperCameraGazer;
  80773. }(VRExperienceHelperGazer));
  80774. /**
  80775. * Helps to quickly add VR support to an existing scene.
  80776. * See http://doc.babylonjs.com/how_to/webvr_helper
  80777. */
  80778. var VRExperienceHelper = /** @class */ (function () {
  80779. /**
  80780. * Instantiates a VRExperienceHelper.
  80781. * Helps to quickly add VR support to an existing scene.
  80782. * @param scene The scene the VRExperienceHelper belongs to.
  80783. * @param webVROptions Options to modify the vr experience helper's behavior.
  80784. */
  80785. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80786. if (webVROptions === void 0) { webVROptions = {}; }
  80787. var _this = this;
  80788. this.webVROptions = webVROptions;
  80789. // Can the system support WebVR, even if a headset isn't plugged in?
  80790. this._webVRsupported = false;
  80791. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80792. this._webVRready = false;
  80793. // Are we waiting for the requestPresent callback to complete?
  80794. this._webVRrequesting = false;
  80795. // Are we presenting to the headset right now?
  80796. this._webVRpresenting = false;
  80797. // Are we presenting in the fullscreen fallback?
  80798. this._fullscreenVRpresenting = false;
  80799. /**
  80800. * Observable raised when entering VR.
  80801. */
  80802. this.onEnteringVRObservable = new BABYLON.Observable();
  80803. /**
  80804. * Observable raised when exiting VR.
  80805. */
  80806. this.onExitingVRObservable = new BABYLON.Observable();
  80807. /**
  80808. * Observable raised when controller mesh is loaded.
  80809. */
  80810. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80811. this._useCustomVRButton = false;
  80812. this._teleportationRequested = false;
  80813. this._teleportActive = false;
  80814. this._floorMeshesCollection = [];
  80815. this._rotationAllowed = true;
  80816. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80817. this._rotationRightAsked = false;
  80818. this._rotationLeftAsked = false;
  80819. this._isDefaultTeleportationTarget = true;
  80820. this._teleportationFillColor = "#444444";
  80821. this._teleportationBorderColor = "#FFFFFF";
  80822. this._rotationAngle = 0;
  80823. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80824. this._padSensibilityUp = 0.65;
  80825. this._padSensibilityDown = 0.35;
  80826. this.leftController = null;
  80827. this.rightController = null;
  80828. /**
  80829. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80830. */
  80831. this.onNewMeshSelected = new BABYLON.Observable();
  80832. /**
  80833. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80834. */
  80835. this.onNewMeshPicked = new BABYLON.Observable();
  80836. /**
  80837. * Observable raised before camera teleportation
  80838. */
  80839. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80840. /**
  80841. * Observable raised after camera teleportation
  80842. */
  80843. this.onAfterCameraTeleport = new BABYLON.Observable();
  80844. /**
  80845. * Observable raised when current selected mesh gets unselected
  80846. */
  80847. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80848. /**
  80849. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80850. */
  80851. this.teleportationEnabled = true;
  80852. this._teleportationInitialized = false;
  80853. this._interactionsEnabled = false;
  80854. this._interactionsRequested = false;
  80855. this._displayGaze = true;
  80856. this._displayLaserPointer = true;
  80857. this._onResize = function () {
  80858. _this.moveButtonToBottomRight();
  80859. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80860. _this.exitVR();
  80861. }
  80862. };
  80863. this._onFullscreenChange = function () {
  80864. if (document.fullscreen !== undefined) {
  80865. _this._fullscreenVRpresenting = document.fullscreen;
  80866. }
  80867. else if (document.mozFullScreen !== undefined) {
  80868. _this._fullscreenVRpresenting = document.mozFullScreen;
  80869. }
  80870. else if (document.webkitIsFullScreen !== undefined) {
  80871. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80872. }
  80873. else if (document.msIsFullScreen !== undefined) {
  80874. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80875. }
  80876. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80877. _this.exitVR();
  80878. if (!_this._useCustomVRButton) {
  80879. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80880. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80881. }
  80882. }
  80883. };
  80884. this.beforeRender = function () {
  80885. if (_this.leftController && _this.leftController._activePointer) {
  80886. _this._castRayAndSelectObject(_this.leftController);
  80887. }
  80888. if (_this.rightController && _this.rightController._activePointer) {
  80889. _this._castRayAndSelectObject(_this.rightController);
  80890. }
  80891. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80892. _this._castRayAndSelectObject(_this._cameraGazer);
  80893. }
  80894. else {
  80895. _this._cameraGazer._gazeTracker.isVisible = false;
  80896. }
  80897. };
  80898. this._onNewGamepadConnected = function (gamepad) {
  80899. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80900. if (gamepad.leftStick) {
  80901. gamepad.onleftstickchanged(function (stickValues) {
  80902. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80903. // Listening to classic/xbox gamepad only if no VR controller is active
  80904. if ((!_this.leftController && !_this.rightController) ||
  80905. ((_this.leftController && !_this.leftController._activePointer) &&
  80906. (_this.rightController && !_this.rightController._activePointer))) {
  80907. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80908. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80909. }
  80910. }
  80911. });
  80912. }
  80913. if (gamepad.rightStick) {
  80914. gamepad.onrightstickchanged(function (stickValues) {
  80915. if (_this._teleportationInitialized) {
  80916. _this._checkRotate(stickValues, _this._cameraGazer);
  80917. }
  80918. });
  80919. }
  80920. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80921. gamepad.onbuttondown(function (buttonPressed) {
  80922. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80923. _this._cameraGazer._selectionPointerDown();
  80924. }
  80925. });
  80926. gamepad.onbuttonup(function (buttonPressed) {
  80927. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80928. _this._cameraGazer._selectionPointerUp();
  80929. }
  80930. });
  80931. }
  80932. }
  80933. else {
  80934. var webVRController = gamepad;
  80935. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80936. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80937. _this.rightController = controller;
  80938. }
  80939. else {
  80940. _this.leftController = controller;
  80941. }
  80942. _this._tryEnableInteractionOnController(controller);
  80943. }
  80944. };
  80945. // 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
  80946. this._tryEnableInteractionOnController = function (controller) {
  80947. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80948. _this._enableInteractionOnController(controller);
  80949. }
  80950. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80951. _this._enableTeleportationOnController(controller);
  80952. }
  80953. };
  80954. this._onNewGamepadDisconnected = function (gamepad) {
  80955. if (gamepad instanceof BABYLON.WebVRController) {
  80956. if (gamepad.hand === "left" && _this.leftController != null) {
  80957. _this.leftController.dispose();
  80958. _this.leftController = null;
  80959. }
  80960. if (gamepad.hand === "right" && _this.rightController != null) {
  80961. _this.rightController.dispose();
  80962. _this.rightController = null;
  80963. }
  80964. }
  80965. };
  80966. this._workingVector = BABYLON.Vector3.Zero();
  80967. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80968. this._workingMatrix = BABYLON.Matrix.Identity();
  80969. this._scene = scene;
  80970. this._canvas = scene.getEngine().getRenderingCanvas();
  80971. // Parse options
  80972. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80973. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80974. }
  80975. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80976. webVROptions.createDeviceOrientationCamera = true;
  80977. }
  80978. if (webVROptions.defaultHeight === undefined) {
  80979. webVROptions.defaultHeight = 1.7;
  80980. }
  80981. if (webVROptions.useCustomVRButton) {
  80982. this._useCustomVRButton = true;
  80983. if (webVROptions.customVRButton) {
  80984. this._btnVR = webVROptions.customVRButton;
  80985. }
  80986. }
  80987. if (webVROptions.rayLength) {
  80988. this._rayLength = webVROptions.rayLength;
  80989. }
  80990. this._defaultHeight = webVROptions.defaultHeight;
  80991. if (webVROptions.positionScale) {
  80992. this._rayLength *= webVROptions.positionScale;
  80993. this._defaultHeight *= webVROptions.positionScale;
  80994. }
  80995. // Set position
  80996. if (this._scene.activeCamera) {
  80997. this._position = this._scene.activeCamera.position.clone();
  80998. }
  80999. else {
  81000. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81001. }
  81002. // Set non-vr camera
  81003. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81004. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81005. // Copy data from existing camera
  81006. if (this._scene.activeCamera) {
  81007. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81008. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81009. // Set rotation from previous camera
  81010. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81011. var targetCamera = this._scene.activeCamera;
  81012. if (targetCamera.rotationQuaternion) {
  81013. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81014. }
  81015. else {
  81016. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81017. }
  81018. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81019. }
  81020. }
  81021. this._scene.activeCamera = this._deviceOrientationCamera;
  81022. if (this._canvas) {
  81023. this._scene.activeCamera.attachControl(this._canvas);
  81024. }
  81025. }
  81026. else {
  81027. this._existingCamera = this._scene.activeCamera;
  81028. }
  81029. // Create VR cameras
  81030. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81031. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81032. }
  81033. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81034. this._webVRCamera.useStandingMatrix();
  81035. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81036. // Create default button
  81037. if (!this._useCustomVRButton) {
  81038. this._btnVR = document.createElement("BUTTON");
  81039. this._btnVR.className = "babylonVRicon";
  81040. this._btnVR.id = "babylonVRiconbtn";
  81041. this._btnVR.title = "Click to switch to VR";
  81042. 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) }";
  81043. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81044. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81045. // css += ".babylonVRicon.vrdisplaysupported { }";
  81046. // css += ".babylonVRicon.vrdisplayready { }";
  81047. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81048. var style = document.createElement('style');
  81049. style.appendChild(document.createTextNode(css));
  81050. document.getElementsByTagName('head')[0].appendChild(style);
  81051. this.moveButtonToBottomRight();
  81052. }
  81053. // VR button click event
  81054. if (this._btnVR) {
  81055. this._btnVR.addEventListener("click", function () {
  81056. if (!_this.isInVRMode) {
  81057. _this.enterVR();
  81058. }
  81059. else {
  81060. _this.exitVR();
  81061. }
  81062. });
  81063. }
  81064. // Window events
  81065. window.addEventListener("resize", this._onResize);
  81066. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81067. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81068. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81069. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81070. // Display vr button when headset is connected
  81071. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81072. this.displayVRButton();
  81073. }
  81074. else {
  81075. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81076. if (e.vrDisplay) {
  81077. _this.displayVRButton();
  81078. }
  81079. });
  81080. }
  81081. // Exiting VR mode using 'ESC' key on desktop
  81082. this._onKeyDown = function (event) {
  81083. if (event.keyCode === 27 && _this.isInVRMode) {
  81084. _this.exitVR();
  81085. }
  81086. };
  81087. document.addEventListener("keydown", this._onKeyDown);
  81088. // Exiting VR mode double tapping the touch screen
  81089. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81090. if (_this.isInVRMode) {
  81091. _this.exitVR();
  81092. if (_this._fullscreenVRpresenting) {
  81093. _this._scene.getEngine().switchFullscreen(true);
  81094. }
  81095. }
  81096. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81097. // Listen for WebVR display changes
  81098. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81099. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81100. this._onVRRequestPresentStart = function () {
  81101. _this._webVRrequesting = true;
  81102. _this.updateButtonVisibility();
  81103. };
  81104. this._onVRRequestPresentComplete = function (success) {
  81105. _this._webVRrequesting = false;
  81106. _this.updateButtonVisibility();
  81107. };
  81108. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81109. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81110. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81111. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81112. scene.onDisposeObservable.add(function () {
  81113. _this.dispose();
  81114. });
  81115. // Gamepad connection events
  81116. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81117. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81118. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81119. this.updateButtonVisibility();
  81120. //create easing functions
  81121. this._circleEase = new BABYLON.CircleEase();
  81122. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81123. }
  81124. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81125. /** Return this.onEnteringVRObservable
  81126. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81127. */
  81128. get: function () {
  81129. return this.onEnteringVRObservable;
  81130. },
  81131. enumerable: true,
  81132. configurable: true
  81133. });
  81134. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81135. /** Return this.onExitingVRObservable
  81136. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81137. */
  81138. get: function () {
  81139. return this.onExitingVRObservable;
  81140. },
  81141. enumerable: true,
  81142. configurable: true
  81143. });
  81144. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81145. /** Return this.onControllerMeshLoadedObservable
  81146. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81147. */
  81148. get: function () {
  81149. return this.onControllerMeshLoadedObservable;
  81150. },
  81151. enumerable: true,
  81152. configurable: true
  81153. });
  81154. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81155. /**
  81156. * The mesh used to display where the user is going to teleport.
  81157. */
  81158. get: function () {
  81159. return this._teleportationTarget;
  81160. },
  81161. /**
  81162. * Sets the mesh to be used to display where the user is going to teleport.
  81163. */
  81164. set: function (value) {
  81165. if (value) {
  81166. value.name = "teleportationTarget";
  81167. this._isDefaultTeleportationTarget = false;
  81168. this._teleportationTarget = value;
  81169. }
  81170. },
  81171. enumerable: true,
  81172. configurable: true
  81173. });
  81174. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81175. /**
  81176. * The mesh used to display where the user is selecting,
  81177. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81178. * See http://doc.babylonjs.com/resources/baking_transformations
  81179. */
  81180. get: function () {
  81181. return this._cameraGazer._gazeTracker;
  81182. },
  81183. set: function (value) {
  81184. if (value) {
  81185. this._cameraGazer._gazeTracker = value;
  81186. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81187. this._cameraGazer._gazeTracker.isPickable = false;
  81188. this._cameraGazer._gazeTracker.isVisible = false;
  81189. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81190. if (this.leftController) {
  81191. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81192. }
  81193. if (this.rightController) {
  81194. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81195. }
  81196. }
  81197. },
  81198. enumerable: true,
  81199. configurable: true
  81200. });
  81201. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81202. /**
  81203. * If the ray of the gaze should be displayed.
  81204. */
  81205. get: function () {
  81206. return this._displayGaze;
  81207. },
  81208. /**
  81209. * Sets if the ray of the gaze should be displayed.
  81210. */
  81211. set: function (value) {
  81212. this._displayGaze = value;
  81213. if (!value) {
  81214. this._cameraGazer._gazeTracker.isVisible = false;
  81215. if (this.leftController) {
  81216. this.leftController._gazeTracker.isVisible = false;
  81217. }
  81218. if (this.rightController) {
  81219. this.rightController._gazeTracker.isVisible = false;
  81220. }
  81221. }
  81222. },
  81223. enumerable: true,
  81224. configurable: true
  81225. });
  81226. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81227. /**
  81228. * If the ray of the LaserPointer should be displayed.
  81229. */
  81230. get: function () {
  81231. return this._displayLaserPointer;
  81232. },
  81233. /**
  81234. * Sets if the ray of the LaserPointer should be displayed.
  81235. */
  81236. set: function (value) {
  81237. this._displayLaserPointer = value;
  81238. if (!value) {
  81239. if (this.rightController) {
  81240. this.rightController._deactivatePointer();
  81241. this.rightController._gazeTracker.isVisible = false;
  81242. }
  81243. if (this.leftController) {
  81244. this.leftController._deactivatePointer();
  81245. this.leftController._gazeTracker.isVisible = false;
  81246. }
  81247. }
  81248. else {
  81249. if (this.rightController) {
  81250. this.rightController._activatePointer();
  81251. }
  81252. else if (this.leftController) {
  81253. this.leftController._activatePointer();
  81254. }
  81255. }
  81256. },
  81257. enumerable: true,
  81258. configurable: true
  81259. });
  81260. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81261. /**
  81262. * The deviceOrientationCamera used as the camera when not in VR.
  81263. */
  81264. get: function () {
  81265. return this._deviceOrientationCamera;
  81266. },
  81267. enumerable: true,
  81268. configurable: true
  81269. });
  81270. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81271. /**
  81272. * Based on the current WebVR support, returns the current VR camera used.
  81273. */
  81274. get: function () {
  81275. if (this._webVRready) {
  81276. return this._webVRCamera;
  81277. }
  81278. else {
  81279. return this._scene.activeCamera;
  81280. }
  81281. },
  81282. enumerable: true,
  81283. configurable: true
  81284. });
  81285. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81286. /**
  81287. * The webVRCamera which is used when in VR.
  81288. */
  81289. get: function () {
  81290. return this._webVRCamera;
  81291. },
  81292. enumerable: true,
  81293. configurable: true
  81294. });
  81295. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81296. /**
  81297. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81298. */
  81299. get: function () {
  81300. return this._vrDeviceOrientationCamera;
  81301. },
  81302. enumerable: true,
  81303. configurable: true
  81304. });
  81305. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81306. get: function () {
  81307. var result = this._cameraGazer._teleportationRequestInitiated
  81308. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81309. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81310. return result;
  81311. },
  81312. enumerable: true,
  81313. configurable: true
  81314. });
  81315. // Raised when one of the controller has loaded successfully its associated default mesh
  81316. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81317. if (this.leftController && this.leftController.webVRController == webVRController) {
  81318. if (webVRController.mesh) {
  81319. this.leftController._setLaserPointerParent(webVRController.mesh);
  81320. }
  81321. }
  81322. if (this.rightController && this.rightController.webVRController == webVRController) {
  81323. if (webVRController.mesh) {
  81324. this.rightController._setLaserPointerParent(webVRController.mesh);
  81325. }
  81326. }
  81327. try {
  81328. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81329. }
  81330. catch (err) {
  81331. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81332. }
  81333. };
  81334. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81335. /**
  81336. * Gets a value indicating if we are currently in VR mode.
  81337. */
  81338. get: function () {
  81339. return this._webVRpresenting || this._fullscreenVRpresenting;
  81340. },
  81341. enumerable: true,
  81342. configurable: true
  81343. });
  81344. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81345. var vrDisplay = this._scene.getEngine().getVRDevice();
  81346. if (vrDisplay) {
  81347. var wasPresenting = this._webVRpresenting;
  81348. // A VR display is connected
  81349. this._webVRpresenting = vrDisplay.isPresenting;
  81350. if (wasPresenting && !this._webVRpresenting)
  81351. this.exitVR();
  81352. }
  81353. else {
  81354. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81355. }
  81356. this.updateButtonVisibility();
  81357. };
  81358. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81359. this._webVRsupported = eventArgs.vrSupported;
  81360. this._webVRready = !!eventArgs.vrDisplay;
  81361. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81362. this.updateButtonVisibility();
  81363. };
  81364. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81365. if (this._canvas && !this._useCustomVRButton) {
  81366. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81367. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81368. }
  81369. };
  81370. VRExperienceHelper.prototype.displayVRButton = function () {
  81371. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81372. document.body.appendChild(this._btnVR);
  81373. this._btnVRDisplayed = true;
  81374. }
  81375. };
  81376. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81377. if (!this._btnVR || this._useCustomVRButton) {
  81378. return;
  81379. }
  81380. this._btnVR.className = "babylonVRicon";
  81381. if (this.isInVRMode) {
  81382. this._btnVR.className += " vrdisplaypresenting";
  81383. }
  81384. else {
  81385. if (this._webVRready)
  81386. this._btnVR.className += " vrdisplayready";
  81387. if (this._webVRsupported)
  81388. this._btnVR.className += " vrdisplaysupported";
  81389. if (this._webVRrequesting)
  81390. this._btnVR.className += " vrdisplayrequesting";
  81391. }
  81392. };
  81393. /**
  81394. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81395. * Otherwise, will use the fullscreen API.
  81396. */
  81397. VRExperienceHelper.prototype.enterVR = function () {
  81398. if (this.onEnteringVRObservable) {
  81399. try {
  81400. this.onEnteringVRObservable.notifyObservers(this);
  81401. }
  81402. catch (err) {
  81403. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81404. }
  81405. }
  81406. if (this._scene.activeCamera) {
  81407. this._position = this._scene.activeCamera.position.clone();
  81408. // make sure that we return to the last active camera
  81409. this._existingCamera = this._scene.activeCamera;
  81410. }
  81411. if (this._webVRrequesting)
  81412. return;
  81413. // If WebVR is supported and a headset is connected
  81414. if (this._webVRready) {
  81415. if (!this._webVRpresenting) {
  81416. this._webVRCamera.position = this._position;
  81417. this._scene.activeCamera = this._webVRCamera;
  81418. }
  81419. }
  81420. else if (this._vrDeviceOrientationCamera) {
  81421. this._vrDeviceOrientationCamera.position = this._position;
  81422. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81423. this._scene.getEngine().switchFullscreen(true);
  81424. this.updateButtonVisibility();
  81425. }
  81426. if (this._scene.activeCamera && this._canvas) {
  81427. this._scene.activeCamera.attachControl(this._canvas);
  81428. }
  81429. if (this._interactionsEnabled) {
  81430. this._scene.registerBeforeRender(this.beforeRender);
  81431. }
  81432. };
  81433. /**
  81434. * Attempt to exit VR, or fullscreen.
  81435. */
  81436. VRExperienceHelper.prototype.exitVR = function () {
  81437. if (this.onExitingVRObservable) {
  81438. try {
  81439. this.onExitingVRObservable.notifyObservers(this);
  81440. }
  81441. catch (err) {
  81442. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81443. }
  81444. }
  81445. if (this._webVRpresenting) {
  81446. this._scene.getEngine().disableVR();
  81447. }
  81448. if (this._scene.activeCamera) {
  81449. this._position = this._scene.activeCamera.position.clone();
  81450. }
  81451. if (this._deviceOrientationCamera) {
  81452. this._deviceOrientationCamera.position = this._position;
  81453. this._scene.activeCamera = this._deviceOrientationCamera;
  81454. if (this._canvas) {
  81455. this._scene.activeCamera.attachControl(this._canvas);
  81456. }
  81457. }
  81458. else if (this._existingCamera) {
  81459. this._existingCamera.position = this._position;
  81460. this._scene.activeCamera = this._existingCamera;
  81461. }
  81462. this.updateButtonVisibility();
  81463. if (this._interactionsEnabled) {
  81464. this._scene.unregisterBeforeRender(this.beforeRender);
  81465. }
  81466. };
  81467. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81468. /**
  81469. * The position of the vr experience helper.
  81470. */
  81471. get: function () {
  81472. return this._position;
  81473. },
  81474. /**
  81475. * Sets the position of the vr experience helper.
  81476. */
  81477. set: function (value) {
  81478. this._position = value;
  81479. if (this._scene.activeCamera) {
  81480. this._scene.activeCamera.position = value;
  81481. }
  81482. },
  81483. enumerable: true,
  81484. configurable: true
  81485. });
  81486. /**
  81487. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81488. */
  81489. VRExperienceHelper.prototype.enableInteractions = function () {
  81490. var _this = this;
  81491. if (!this._interactionsEnabled) {
  81492. this._interactionsRequested = true;
  81493. if (this.leftController) {
  81494. this._enableInteractionOnController(this.leftController);
  81495. }
  81496. if (this.rightController) {
  81497. this._enableInteractionOnController(this.rightController);
  81498. }
  81499. this.raySelectionPredicate = function (mesh) {
  81500. return mesh.isVisible;
  81501. };
  81502. this.meshSelectionPredicate = function (mesh) {
  81503. return true;
  81504. };
  81505. this._raySelectionPredicate = function (mesh) {
  81506. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81507. && mesh.name.indexOf("teleportationTarget") === -1
  81508. && mesh.name.indexOf("torusTeleportation") === -1
  81509. && mesh.name.indexOf("laserPointer") === -1)) {
  81510. return _this.raySelectionPredicate(mesh);
  81511. }
  81512. return false;
  81513. };
  81514. this._interactionsEnabled = true;
  81515. }
  81516. };
  81517. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81518. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81519. if (this._floorMeshesCollection[i].id === mesh.id) {
  81520. return true;
  81521. }
  81522. }
  81523. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81524. return true;
  81525. }
  81526. return false;
  81527. };
  81528. /**
  81529. * Adds a floor mesh to be used for teleportation.
  81530. * @param floorMesh the mesh to be used for teleportation.
  81531. */
  81532. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81533. if (!this._floorMeshesCollection) {
  81534. return;
  81535. }
  81536. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81537. return;
  81538. }
  81539. this._floorMeshesCollection.push(floorMesh);
  81540. };
  81541. /**
  81542. * Removes a floor mesh from being used for teleportation.
  81543. * @param floorMesh the mesh to be removed.
  81544. */
  81545. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81546. if (!this._floorMeshesCollection) {
  81547. return;
  81548. }
  81549. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81550. if (meshIndex !== -1) {
  81551. this._floorMeshesCollection.splice(meshIndex, 1);
  81552. }
  81553. };
  81554. /**
  81555. * Enables interactions and teleportation using the VR controllers and gaze.
  81556. * @param vrTeleportationOptions options to modify teleportation behavior.
  81557. */
  81558. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81559. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81560. if (!this._teleportationInitialized) {
  81561. this._teleportationRequested = true;
  81562. this.enableInteractions();
  81563. if (vrTeleportationOptions.floorMeshName) {
  81564. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81565. }
  81566. if (vrTeleportationOptions.floorMeshes) {
  81567. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81568. }
  81569. if (this.leftController != null) {
  81570. this._enableTeleportationOnController(this.leftController);
  81571. }
  81572. if (this.rightController != null) {
  81573. this._enableTeleportationOnController(this.rightController);
  81574. }
  81575. // Creates an image processing post process for the vignette not relying
  81576. // on the main scene configuration for image processing to reduce setup and spaces
  81577. // (gamma/linear) conflicts.
  81578. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81579. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81580. imageProcessingConfiguration.vignetteEnabled = true;
  81581. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81582. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81583. this._teleportationInitialized = true;
  81584. if (this._isDefaultTeleportationTarget) {
  81585. this._createTeleportationCircles();
  81586. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81587. }
  81588. }
  81589. };
  81590. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81591. var _this = this;
  81592. var controllerMesh = controller.webVRController.mesh;
  81593. if (controllerMesh) {
  81594. controller._interactionsEnabled = true;
  81595. controller._activatePointer();
  81596. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81597. // Enabling / disabling laserPointer
  81598. if (_this._displayLaserPointer && stateObject.value === 1) {
  81599. if (controller._activePointer) {
  81600. controller._deactivatePointer();
  81601. }
  81602. else {
  81603. controller._activatePointer();
  81604. }
  81605. if (_this.displayGaze) {
  81606. controller._gazeTracker.isVisible = controller._activePointer;
  81607. }
  81608. }
  81609. });
  81610. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81611. if (!controller._pointerDownOnMeshAsked) {
  81612. if (stateObject.value > _this._padSensibilityUp) {
  81613. controller._selectionPointerDown();
  81614. }
  81615. }
  81616. else if (stateObject.value < _this._padSensibilityDown) {
  81617. controller._selectionPointerUp();
  81618. }
  81619. });
  81620. }
  81621. };
  81622. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81623. // Dont teleport if another gaze already requested teleportation
  81624. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81625. return;
  81626. }
  81627. if (!gazer._teleportationRequestInitiated) {
  81628. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81629. gazer._activatePointer();
  81630. gazer._teleportationRequestInitiated = true;
  81631. }
  81632. }
  81633. else {
  81634. // Listening to the proper controller values changes to confirm teleportation
  81635. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81636. if (this._teleportActive) {
  81637. this._teleportCamera(this._haloCenter);
  81638. }
  81639. gazer._teleportationRequestInitiated = false;
  81640. }
  81641. }
  81642. };
  81643. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81644. // Only rotate when user is not currently selecting a teleportation location
  81645. if (gazer._teleportationRequestInitiated) {
  81646. return;
  81647. }
  81648. if (!this._rotationLeftAsked) {
  81649. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81650. this._rotationLeftAsked = true;
  81651. if (this._rotationAllowed) {
  81652. this._rotateCamera(false);
  81653. }
  81654. }
  81655. }
  81656. else {
  81657. if (stateObject.x > -this._padSensibilityDown) {
  81658. this._rotationLeftAsked = false;
  81659. }
  81660. }
  81661. if (!this._rotationRightAsked) {
  81662. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81663. this._rotationRightAsked = true;
  81664. if (this._rotationAllowed) {
  81665. this._rotateCamera(true);
  81666. }
  81667. }
  81668. }
  81669. else {
  81670. if (stateObject.x < this._padSensibilityDown) {
  81671. this._rotationRightAsked = false;
  81672. }
  81673. }
  81674. };
  81675. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81676. // Only teleport backwards when user is not currently selecting a teleportation location
  81677. if (gazer._teleportationRequestInitiated) {
  81678. return;
  81679. }
  81680. // Teleport backwards
  81681. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81682. if (!gazer._teleportationBackRequestInitiated) {
  81683. if (!this.currentVRCamera) {
  81684. return;
  81685. }
  81686. // Get rotation and position of the current camera
  81687. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81688. var position = this.currentVRCamera.position;
  81689. // If the camera has device position, use that instead
  81690. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81691. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81692. position = this.currentVRCamera.devicePosition;
  81693. }
  81694. // Get matrix with only the y rotation of the device rotation
  81695. rotation.toEulerAnglesToRef(this._workingVector);
  81696. this._workingVector.z = 0;
  81697. this._workingVector.x = 0;
  81698. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81699. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81700. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81701. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81702. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81703. var ray = new BABYLON.Ray(position, this._workingVector);
  81704. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81705. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81706. this._teleportCamera(hit.pickedPoint);
  81707. }
  81708. gazer._teleportationBackRequestInitiated = true;
  81709. }
  81710. }
  81711. else {
  81712. gazer._teleportationBackRequestInitiated = false;
  81713. }
  81714. };
  81715. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81716. var _this = this;
  81717. var controllerMesh = controller.webVRController.mesh;
  81718. if (controllerMesh) {
  81719. if (!controller._interactionsEnabled) {
  81720. this._enableInteractionOnController(controller);
  81721. }
  81722. controller._interactionsEnabled = true;
  81723. controller._teleportationEnabled = true;
  81724. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81725. controller._dpadPressed = false;
  81726. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81727. controller._dpadPressed = stateObject.pressed;
  81728. if (!controller._dpadPressed) {
  81729. _this._rotationLeftAsked = false;
  81730. _this._rotationRightAsked = false;
  81731. controller._teleportationBackRequestInitiated = false;
  81732. }
  81733. });
  81734. }
  81735. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81736. if (_this.teleportationEnabled) {
  81737. _this._checkTeleportBackwards(stateObject, controller);
  81738. _this._checkTeleportWithRay(stateObject, controller);
  81739. }
  81740. _this._checkRotate(stateObject, controller);
  81741. });
  81742. }
  81743. };
  81744. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81745. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81746. this._teleportationTarget.isPickable = false;
  81747. var length = 512;
  81748. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81749. dynamicTexture.hasAlpha = true;
  81750. var context = dynamicTexture.getContext();
  81751. var centerX = length / 2;
  81752. var centerY = length / 2;
  81753. var radius = 200;
  81754. context.beginPath();
  81755. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81756. context.fillStyle = this._teleportationFillColor;
  81757. context.fill();
  81758. context.lineWidth = 10;
  81759. context.strokeStyle = this._teleportationBorderColor;
  81760. context.stroke();
  81761. context.closePath();
  81762. dynamicTexture.update();
  81763. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81764. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81765. this._teleportationTarget.material = teleportationCircleMaterial;
  81766. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81767. torus.isPickable = false;
  81768. torus.parent = this._teleportationTarget;
  81769. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81770. var keys = [];
  81771. keys.push({
  81772. frame: 0,
  81773. value: 0
  81774. });
  81775. keys.push({
  81776. frame: 30,
  81777. value: 0.4
  81778. });
  81779. keys.push({
  81780. frame: 60,
  81781. value: 0
  81782. });
  81783. animationInnerCircle.setKeys(keys);
  81784. var easingFunction = new BABYLON.SineEase();
  81785. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81786. animationInnerCircle.setEasingFunction(easingFunction);
  81787. torus.animations = [];
  81788. torus.animations.push(animationInnerCircle);
  81789. this._scene.beginAnimation(torus, 0, 60, true);
  81790. this._hideTeleportationTarget();
  81791. };
  81792. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81793. this._teleportActive = true;
  81794. if (this._teleportationInitialized) {
  81795. this._teleportationTarget.isVisible = true;
  81796. if (this._isDefaultTeleportationTarget) {
  81797. this._teleportationTarget.getChildren()[0].isVisible = true;
  81798. }
  81799. }
  81800. };
  81801. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81802. this._teleportActive = false;
  81803. if (this._teleportationInitialized) {
  81804. this._teleportationTarget.isVisible = false;
  81805. if (this._isDefaultTeleportationTarget) {
  81806. this._teleportationTarget.getChildren()[0].isVisible = false;
  81807. }
  81808. }
  81809. };
  81810. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81811. var _this = this;
  81812. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81813. return;
  81814. }
  81815. if (right) {
  81816. this._rotationAngle++;
  81817. }
  81818. else {
  81819. this._rotationAngle--;
  81820. }
  81821. this.currentVRCamera.animations = [];
  81822. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81823. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81824. var animationRotationKeys = [];
  81825. animationRotationKeys.push({
  81826. frame: 0,
  81827. value: this.currentVRCamera.rotationQuaternion
  81828. });
  81829. animationRotationKeys.push({
  81830. frame: 6,
  81831. value: target
  81832. });
  81833. animationRotation.setKeys(animationRotationKeys);
  81834. animationRotation.setEasingFunction(this._circleEase);
  81835. this.currentVRCamera.animations.push(animationRotation);
  81836. this._postProcessMove.animations = [];
  81837. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81838. var vignetteWeightKeys = [];
  81839. vignetteWeightKeys.push({
  81840. frame: 0,
  81841. value: 0
  81842. });
  81843. vignetteWeightKeys.push({
  81844. frame: 3,
  81845. value: 4
  81846. });
  81847. vignetteWeightKeys.push({
  81848. frame: 6,
  81849. value: 0
  81850. });
  81851. animationPP.setKeys(vignetteWeightKeys);
  81852. animationPP.setEasingFunction(this._circleEase);
  81853. this._postProcessMove.animations.push(animationPP);
  81854. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81855. var vignetteStretchKeys = [];
  81856. vignetteStretchKeys.push({
  81857. frame: 0,
  81858. value: 0
  81859. });
  81860. vignetteStretchKeys.push({
  81861. frame: 3,
  81862. value: 10
  81863. });
  81864. vignetteStretchKeys.push({
  81865. frame: 6,
  81866. value: 0
  81867. });
  81868. animationPP2.setKeys(vignetteStretchKeys);
  81869. animationPP2.setEasingFunction(this._circleEase);
  81870. this._postProcessMove.animations.push(animationPP2);
  81871. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81872. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81873. this._postProcessMove.samples = 4;
  81874. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81875. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81876. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81877. });
  81878. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81879. };
  81880. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81881. if (hit.pickedPoint) {
  81882. if (gazer._teleportationRequestInitiated) {
  81883. this._displayTeleportationTarget();
  81884. this._haloCenter.copyFrom(hit.pickedPoint);
  81885. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81886. }
  81887. var pickNormal = hit.getNormal(true, false);
  81888. if (pickNormal) {
  81889. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81890. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81891. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81892. }
  81893. this._teleportationTarget.position.y += 0.1;
  81894. }
  81895. };
  81896. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81897. var _this = this;
  81898. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81899. return;
  81900. }
  81901. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81902. // offset of the headset from the anchor.
  81903. if (this.webVRCamera.leftCamera) {
  81904. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81905. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81906. location.subtractToRef(this._workingVector, this._workingVector);
  81907. }
  81908. else {
  81909. this._workingVector.copyFrom(location);
  81910. }
  81911. // Add height to account for user's height offset
  81912. if (this.isInVRMode) {
  81913. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81914. }
  81915. else {
  81916. this._workingVector.y += this._defaultHeight;
  81917. }
  81918. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81919. // Create animation from the camera's position to the new location
  81920. this.currentVRCamera.animations = [];
  81921. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81922. var animationCameraTeleportationKeys = [{
  81923. frame: 0,
  81924. value: this.currentVRCamera.position
  81925. },
  81926. {
  81927. frame: 11,
  81928. value: this._workingVector
  81929. }
  81930. ];
  81931. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81932. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81933. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81934. this._postProcessMove.animations = [];
  81935. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81936. var vignetteWeightKeys = [];
  81937. vignetteWeightKeys.push({
  81938. frame: 0,
  81939. value: 0
  81940. });
  81941. vignetteWeightKeys.push({
  81942. frame: 5,
  81943. value: 8
  81944. });
  81945. vignetteWeightKeys.push({
  81946. frame: 11,
  81947. value: 0
  81948. });
  81949. animationPP.setKeys(vignetteWeightKeys);
  81950. this._postProcessMove.animations.push(animationPP);
  81951. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81952. var vignetteStretchKeys = [];
  81953. vignetteStretchKeys.push({
  81954. frame: 0,
  81955. value: 0
  81956. });
  81957. vignetteStretchKeys.push({
  81958. frame: 5,
  81959. value: 10
  81960. });
  81961. vignetteStretchKeys.push({
  81962. frame: 11,
  81963. value: 0
  81964. });
  81965. animationPP2.setKeys(vignetteStretchKeys);
  81966. this._postProcessMove.animations.push(animationPP2);
  81967. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81968. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81969. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81970. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81971. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81972. });
  81973. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81974. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81975. });
  81976. this._hideTeleportationTarget();
  81977. };
  81978. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81979. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81980. return;
  81981. }
  81982. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81983. // Moving the gazeTracker on the mesh face targetted
  81984. if (hit && hit.pickedPoint) {
  81985. if (this._displayGaze) {
  81986. var multiplier = 1;
  81987. gazer._gazeTracker.isVisible = true;
  81988. if (gazer._isActionableMesh) {
  81989. multiplier = 3;
  81990. }
  81991. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81992. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81993. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81994. var pickNormal = hit.getNormal();
  81995. // To avoid z-fighting
  81996. var deltaFighting = 0.002;
  81997. if (pickNormal) {
  81998. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81999. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82000. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82001. }
  82002. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82003. if (gazer._gazeTracker.position.x < 0) {
  82004. gazer._gazeTracker.position.x += deltaFighting;
  82005. }
  82006. else {
  82007. gazer._gazeTracker.position.x -= deltaFighting;
  82008. }
  82009. if (gazer._gazeTracker.position.y < 0) {
  82010. gazer._gazeTracker.position.y += deltaFighting;
  82011. }
  82012. else {
  82013. gazer._gazeTracker.position.y -= deltaFighting;
  82014. }
  82015. if (gazer._gazeTracker.position.z < 0) {
  82016. gazer._gazeTracker.position.z += deltaFighting;
  82017. }
  82018. else {
  82019. gazer._gazeTracker.position.z -= deltaFighting;
  82020. }
  82021. }
  82022. // Changing the size of the laser pointer based on the distance from the targetted point
  82023. gazer._updatePointerDistance(hit.distance);
  82024. }
  82025. else {
  82026. gazer._gazeTracker.isVisible = false;
  82027. }
  82028. if (hit && hit.pickedMesh) {
  82029. gazer._currentHit = hit;
  82030. if (gazer._pointerDownOnMeshAsked) {
  82031. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82032. }
  82033. // The object selected is the floor, we're in a teleportation scenario
  82034. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82035. // Moving the teleportation area to this targetted point
  82036. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82037. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82038. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82039. }
  82040. gazer._currentMeshSelected = null;
  82041. if (gazer._teleportationRequestInitiated) {
  82042. this._moveTeleportationSelectorTo(hit, gazer);
  82043. }
  82044. return;
  82045. }
  82046. // If not, we're in a selection scenario
  82047. //this._teleportationAllowed = false;
  82048. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82049. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82050. this.onNewMeshPicked.notifyObservers(hit);
  82051. gazer._currentMeshSelected = hit.pickedMesh;
  82052. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82053. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82054. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82055. gazer._isActionableMesh = true;
  82056. }
  82057. else {
  82058. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82059. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82060. gazer._isActionableMesh = false;
  82061. }
  82062. try {
  82063. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82064. }
  82065. catch (err) {
  82066. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82067. }
  82068. }
  82069. else {
  82070. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82071. gazer._currentMeshSelected = null;
  82072. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82073. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82074. }
  82075. }
  82076. }
  82077. else {
  82078. gazer._currentHit = null;
  82079. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82080. gazer._currentMeshSelected = null;
  82081. //this._teleportationAllowed = false;
  82082. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82083. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82084. }
  82085. };
  82086. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82087. if (mesh) {
  82088. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82089. }
  82090. };
  82091. /**
  82092. * Sets the color of the laser ray from the vr controllers.
  82093. * @param color new color for the ray.
  82094. */
  82095. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82096. if (this.leftController) {
  82097. this.leftController._setLaserPointerColor(color);
  82098. }
  82099. if (this.rightController) {
  82100. this.rightController._setLaserPointerColor(color);
  82101. }
  82102. };
  82103. /**
  82104. * Sets the color of the ray from the vr headsets gaze.
  82105. * @param color new color for the ray.
  82106. */
  82107. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82108. if (!this._cameraGazer._gazeTracker.material) {
  82109. return;
  82110. }
  82111. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82112. if (this.leftController) {
  82113. this.leftController._gazeTracker.material.emissiveColor = color;
  82114. }
  82115. if (this.rightController) {
  82116. this.rightController._gazeTracker.material.emissiveColor = color;
  82117. }
  82118. };
  82119. /**
  82120. * Exits VR and disposes of the vr experience helper
  82121. */
  82122. VRExperienceHelper.prototype.dispose = function () {
  82123. if (this.isInVRMode) {
  82124. this.exitVR();
  82125. }
  82126. if (this._postProcessMove) {
  82127. this._postProcessMove.dispose();
  82128. }
  82129. if (this._webVRCamera) {
  82130. this._webVRCamera.dispose();
  82131. }
  82132. if (this._vrDeviceOrientationCamera) {
  82133. this._vrDeviceOrientationCamera.dispose();
  82134. }
  82135. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82136. document.body.removeChild(this._btnVR);
  82137. }
  82138. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82139. this._deviceOrientationCamera.dispose();
  82140. }
  82141. if (this._cameraGazer) {
  82142. this._cameraGazer.dispose();
  82143. }
  82144. if (this.leftController) {
  82145. this.leftController.dispose();
  82146. }
  82147. if (this.rightController) {
  82148. this.rightController.dispose();
  82149. }
  82150. if (this._teleportationTarget) {
  82151. this._teleportationTarget.dispose();
  82152. }
  82153. this._floorMeshesCollection = [];
  82154. document.removeEventListener("keydown", this._onKeyDown);
  82155. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82156. window.removeEventListener("resize", this._onResize);
  82157. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82158. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82159. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82160. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82161. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82162. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82163. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82164. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82165. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82166. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82167. this._scene.unregisterBeforeRender(this.beforeRender);
  82168. };
  82169. /**
  82170. * Gets the name of the VRExperienceHelper class
  82171. * @returns "VRExperienceHelper"
  82172. */
  82173. VRExperienceHelper.prototype.getClassName = function () {
  82174. return "VRExperienceHelper";
  82175. };
  82176. return VRExperienceHelper;
  82177. }());
  82178. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82179. })(BABYLON || (BABYLON = {}));
  82180. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82181. // Mainly based on these 2 articles :
  82182. // 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
  82183. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82184. var BABYLON;
  82185. (function (BABYLON) {
  82186. var JoystickAxis;
  82187. (function (JoystickAxis) {
  82188. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82189. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82190. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82191. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82192. var VirtualJoystick = /** @class */ (function () {
  82193. function VirtualJoystick(leftJoystick) {
  82194. var _this = this;
  82195. if (leftJoystick) {
  82196. this._leftJoystick = true;
  82197. }
  82198. else {
  82199. this._leftJoystick = false;
  82200. }
  82201. VirtualJoystick._globalJoystickIndex++;
  82202. // By default left & right arrow keys are moving the X
  82203. // and up & down keys are moving the Y
  82204. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82205. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82206. this.reverseLeftRight = false;
  82207. this.reverseUpDown = false;
  82208. // collections of pointers
  82209. this._touches = new BABYLON.StringDictionary();
  82210. this.deltaPosition = BABYLON.Vector3.Zero();
  82211. this._joystickSensibility = 25;
  82212. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82213. this._onResize = function (evt) {
  82214. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82215. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82216. if (VirtualJoystick.vjCanvas) {
  82217. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82218. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82219. }
  82220. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82221. };
  82222. // injecting a canvas element on top of the canvas 3D game
  82223. if (!VirtualJoystick.vjCanvas) {
  82224. window.addEventListener("resize", this._onResize, false);
  82225. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82226. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82227. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82228. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82229. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82230. VirtualJoystick.vjCanvas.style.width = "100%";
  82231. VirtualJoystick.vjCanvas.style.height = "100%";
  82232. VirtualJoystick.vjCanvas.style.position = "absolute";
  82233. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82234. VirtualJoystick.vjCanvas.style.top = "0px";
  82235. VirtualJoystick.vjCanvas.style.left = "0px";
  82236. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82237. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82238. // Support for jQuery PEP polyfill
  82239. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82240. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82241. if (!context) {
  82242. throw new Error("Unable to create canvas for virtual joystick");
  82243. }
  82244. VirtualJoystick.vjCanvasContext = context;
  82245. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82246. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82247. document.body.appendChild(VirtualJoystick.vjCanvas);
  82248. }
  82249. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82250. this.pressed = false;
  82251. // default joystick color
  82252. this._joystickColor = "cyan";
  82253. this._joystickPointerID = -1;
  82254. // current joystick position
  82255. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82256. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82257. // origin joystick position
  82258. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82259. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82260. this._onPointerDownHandlerRef = function (evt) {
  82261. _this._onPointerDown(evt);
  82262. };
  82263. this._onPointerMoveHandlerRef = function (evt) {
  82264. _this._onPointerMove(evt);
  82265. };
  82266. this._onPointerUpHandlerRef = function (evt) {
  82267. _this._onPointerUp(evt);
  82268. };
  82269. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82270. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82271. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82272. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82273. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82274. evt.preventDefault(); // Disables system menu
  82275. }, false);
  82276. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82277. }
  82278. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82279. this._joystickSensibility = newJoystickSensibility;
  82280. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82281. };
  82282. VirtualJoystick.prototype._onPointerDown = function (e) {
  82283. var positionOnScreenCondition;
  82284. e.preventDefault();
  82285. if (this._leftJoystick === true) {
  82286. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82287. }
  82288. else {
  82289. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82290. }
  82291. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82292. // First contact will be dedicated to the virtual joystick
  82293. this._joystickPointerID = e.pointerId;
  82294. this._joystickPointerStartPos.x = e.clientX;
  82295. this._joystickPointerStartPos.y = e.clientY;
  82296. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82297. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82298. this._deltaJoystickVector.x = 0;
  82299. this._deltaJoystickVector.y = 0;
  82300. this.pressed = true;
  82301. this._touches.add(e.pointerId.toString(), e);
  82302. }
  82303. else {
  82304. // You can only trigger the action buttons with a joystick declared
  82305. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82306. this._action();
  82307. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82308. }
  82309. }
  82310. };
  82311. VirtualJoystick.prototype._onPointerMove = function (e) {
  82312. // If the current pointer is the one associated to the joystick (first touch contact)
  82313. if (this._joystickPointerID == e.pointerId) {
  82314. this._joystickPointerPos.x = e.clientX;
  82315. this._joystickPointerPos.y = e.clientY;
  82316. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82317. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82318. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82319. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82320. switch (this._axisTargetedByLeftAndRight) {
  82321. case JoystickAxis.X:
  82322. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82323. break;
  82324. case JoystickAxis.Y:
  82325. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82326. break;
  82327. case JoystickAxis.Z:
  82328. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82329. break;
  82330. }
  82331. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82332. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82333. switch (this._axisTargetedByUpAndDown) {
  82334. case JoystickAxis.X:
  82335. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82336. break;
  82337. case JoystickAxis.Y:
  82338. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82339. break;
  82340. case JoystickAxis.Z:
  82341. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82342. break;
  82343. }
  82344. }
  82345. else {
  82346. var data = this._touches.get(e.pointerId.toString());
  82347. if (data) {
  82348. data.x = e.clientX;
  82349. data.y = e.clientY;
  82350. }
  82351. }
  82352. };
  82353. VirtualJoystick.prototype._onPointerUp = function (e) {
  82354. if (this._joystickPointerID == e.pointerId) {
  82355. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82356. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82357. this._joystickPointerID = -1;
  82358. this.pressed = false;
  82359. }
  82360. else {
  82361. var touch = this._touches.get(e.pointerId.toString());
  82362. if (touch) {
  82363. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82364. }
  82365. }
  82366. this._deltaJoystickVector.x = 0;
  82367. this._deltaJoystickVector.y = 0;
  82368. this._touches.remove(e.pointerId.toString());
  82369. };
  82370. /**
  82371. * Change the color of the virtual joystick
  82372. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82373. */
  82374. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82375. this._joystickColor = newColor;
  82376. };
  82377. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82378. this._action = action;
  82379. };
  82380. // Define which axis you'd like to control for left & right
  82381. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82382. switch (axis) {
  82383. case JoystickAxis.X:
  82384. case JoystickAxis.Y:
  82385. case JoystickAxis.Z:
  82386. this._axisTargetedByLeftAndRight = axis;
  82387. break;
  82388. default:
  82389. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82390. break;
  82391. }
  82392. };
  82393. // Define which axis you'd like to control for up & down
  82394. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82395. switch (axis) {
  82396. case JoystickAxis.X:
  82397. case JoystickAxis.Y:
  82398. case JoystickAxis.Z:
  82399. this._axisTargetedByUpAndDown = axis;
  82400. break;
  82401. default:
  82402. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82403. break;
  82404. }
  82405. };
  82406. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82407. var _this = this;
  82408. if (this.pressed) {
  82409. this._touches.forEach(function (key, touch) {
  82410. if (touch.pointerId === _this._joystickPointerID) {
  82411. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82412. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82413. VirtualJoystick.vjCanvasContext.beginPath();
  82414. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82415. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82416. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82417. VirtualJoystick.vjCanvasContext.stroke();
  82418. VirtualJoystick.vjCanvasContext.closePath();
  82419. VirtualJoystick.vjCanvasContext.beginPath();
  82420. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82421. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82422. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82423. VirtualJoystick.vjCanvasContext.stroke();
  82424. VirtualJoystick.vjCanvasContext.closePath();
  82425. VirtualJoystick.vjCanvasContext.beginPath();
  82426. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82427. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82428. VirtualJoystick.vjCanvasContext.stroke();
  82429. VirtualJoystick.vjCanvasContext.closePath();
  82430. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82431. }
  82432. else {
  82433. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82434. VirtualJoystick.vjCanvasContext.beginPath();
  82435. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82436. VirtualJoystick.vjCanvasContext.beginPath();
  82437. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82438. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82439. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82440. VirtualJoystick.vjCanvasContext.stroke();
  82441. VirtualJoystick.vjCanvasContext.closePath();
  82442. touch.prevX = touch.x;
  82443. touch.prevY = touch.y;
  82444. }
  82445. ;
  82446. });
  82447. }
  82448. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82449. };
  82450. VirtualJoystick.prototype.releaseCanvas = function () {
  82451. if (VirtualJoystick.vjCanvas) {
  82452. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82453. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82454. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82455. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82456. window.removeEventListener("resize", this._onResize);
  82457. document.body.removeChild(VirtualJoystick.vjCanvas);
  82458. VirtualJoystick.vjCanvas = null;
  82459. }
  82460. };
  82461. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82462. VirtualJoystick._globalJoystickIndex = 0;
  82463. return VirtualJoystick;
  82464. }());
  82465. BABYLON.VirtualJoystick = VirtualJoystick;
  82466. })(BABYLON || (BABYLON = {}));
  82467. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82468. var BABYLON;
  82469. (function (BABYLON) {
  82470. // We're mainly based on the logic defined into the FreeCamera code
  82471. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82472. __extends(VirtualJoysticksCamera, _super);
  82473. function VirtualJoysticksCamera(name, position, scene) {
  82474. var _this = _super.call(this, name, position, scene) || this;
  82475. _this.inputs.addVirtualJoystick();
  82476. return _this;
  82477. }
  82478. VirtualJoysticksCamera.prototype.getClassName = function () {
  82479. return "VirtualJoysticksCamera";
  82480. };
  82481. return VirtualJoysticksCamera;
  82482. }(BABYLON.FreeCamera));
  82483. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82484. })(BABYLON || (BABYLON = {}));
  82485. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82486. var BABYLON;
  82487. (function (BABYLON) {
  82488. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82489. function FreeCameraVirtualJoystickInput() {
  82490. }
  82491. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82492. return this._leftjoystick;
  82493. };
  82494. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82495. return this._rightjoystick;
  82496. };
  82497. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82498. if (this._leftjoystick) {
  82499. var camera = this.camera;
  82500. var speed = camera._computeLocalCameraSpeed() * 50;
  82501. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82502. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82503. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82504. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82505. if (!this._leftjoystick.pressed) {
  82506. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82507. }
  82508. if (!this._rightjoystick.pressed) {
  82509. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82510. }
  82511. }
  82512. };
  82513. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82514. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82515. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82516. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82517. this._leftjoystick.setJoystickSensibility(0.15);
  82518. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82519. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82520. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82521. this._rightjoystick.reverseUpDown = true;
  82522. this._rightjoystick.setJoystickSensibility(0.05);
  82523. this._rightjoystick.setJoystickColor("yellow");
  82524. };
  82525. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82526. this._leftjoystick.releaseCanvas();
  82527. this._rightjoystick.releaseCanvas();
  82528. };
  82529. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82530. return "FreeCameraVirtualJoystickInput";
  82531. };
  82532. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82533. return "virtualJoystick";
  82534. };
  82535. return FreeCameraVirtualJoystickInput;
  82536. }());
  82537. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82538. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82539. })(BABYLON || (BABYLON = {}));
  82540. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82541. var BABYLON;
  82542. (function (BABYLON) {
  82543. var SimplificationSettings = /** @class */ (function () {
  82544. function SimplificationSettings(quality, distance, optimizeMesh) {
  82545. this.quality = quality;
  82546. this.distance = distance;
  82547. this.optimizeMesh = optimizeMesh;
  82548. }
  82549. return SimplificationSettings;
  82550. }());
  82551. BABYLON.SimplificationSettings = SimplificationSettings;
  82552. var SimplificationQueue = /** @class */ (function () {
  82553. function SimplificationQueue() {
  82554. this.running = false;
  82555. this._simplificationArray = [];
  82556. }
  82557. SimplificationQueue.prototype.addTask = function (task) {
  82558. this._simplificationArray.push(task);
  82559. };
  82560. SimplificationQueue.prototype.executeNext = function () {
  82561. var task = this._simplificationArray.pop();
  82562. if (task) {
  82563. this.running = true;
  82564. this.runSimplification(task);
  82565. }
  82566. else {
  82567. this.running = false;
  82568. }
  82569. };
  82570. SimplificationQueue.prototype.runSimplification = function (task) {
  82571. var _this = this;
  82572. if (task.parallelProcessing) {
  82573. //parallel simplifier
  82574. task.settings.forEach(function (setting) {
  82575. var simplifier = _this.getSimplifier(task);
  82576. simplifier.simplify(setting, function (newMesh) {
  82577. task.mesh.addLODLevel(setting.distance, newMesh);
  82578. newMesh.isVisible = true;
  82579. //check if it is the last
  82580. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82581. //all done, run the success callback.
  82582. task.successCallback();
  82583. }
  82584. _this.executeNext();
  82585. });
  82586. });
  82587. }
  82588. else {
  82589. //single simplifier.
  82590. var simplifier = this.getSimplifier(task);
  82591. var runDecimation = function (setting, callback) {
  82592. simplifier.simplify(setting, function (newMesh) {
  82593. task.mesh.addLODLevel(setting.distance, newMesh);
  82594. newMesh.isVisible = true;
  82595. //run the next quality level
  82596. callback();
  82597. });
  82598. };
  82599. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82600. runDecimation(task.settings[loop.index], function () {
  82601. loop.executeNext();
  82602. });
  82603. }, function () {
  82604. //execution ended, run the success callback.
  82605. if (task.successCallback) {
  82606. task.successCallback();
  82607. }
  82608. _this.executeNext();
  82609. });
  82610. }
  82611. };
  82612. SimplificationQueue.prototype.getSimplifier = function (task) {
  82613. switch (task.simplificationType) {
  82614. case SimplificationType.QUADRATIC:
  82615. default:
  82616. return new QuadraticErrorSimplification(task.mesh);
  82617. }
  82618. };
  82619. return SimplificationQueue;
  82620. }());
  82621. BABYLON.SimplificationQueue = SimplificationQueue;
  82622. /**
  82623. * The implemented types of simplification.
  82624. * At the moment only Quadratic Error Decimation is implemented.
  82625. */
  82626. var SimplificationType;
  82627. (function (SimplificationType) {
  82628. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82629. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82630. var DecimationTriangle = /** @class */ (function () {
  82631. function DecimationTriangle(vertices) {
  82632. this.vertices = vertices;
  82633. this.error = new Array(4);
  82634. this.deleted = false;
  82635. this.isDirty = false;
  82636. this.deletePending = false;
  82637. this.borderFactor = 0;
  82638. }
  82639. return DecimationTriangle;
  82640. }());
  82641. BABYLON.DecimationTriangle = DecimationTriangle;
  82642. var DecimationVertex = /** @class */ (function () {
  82643. function DecimationVertex(position, id) {
  82644. this.position = position;
  82645. this.id = id;
  82646. this.isBorder = true;
  82647. this.q = new QuadraticMatrix();
  82648. this.triangleCount = 0;
  82649. this.triangleStart = 0;
  82650. this.originalOffsets = [];
  82651. }
  82652. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82653. this.position.copyFrom(newPosition);
  82654. };
  82655. return DecimationVertex;
  82656. }());
  82657. BABYLON.DecimationVertex = DecimationVertex;
  82658. var QuadraticMatrix = /** @class */ (function () {
  82659. function QuadraticMatrix(data) {
  82660. this.data = new Array(10);
  82661. for (var i = 0; i < 10; ++i) {
  82662. if (data && data[i]) {
  82663. this.data[i] = data[i];
  82664. }
  82665. else {
  82666. this.data[i] = 0;
  82667. }
  82668. }
  82669. }
  82670. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82671. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82672. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82673. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82674. return det;
  82675. };
  82676. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82677. for (var i = 0; i < 10; ++i) {
  82678. this.data[i] += matrix.data[i];
  82679. }
  82680. };
  82681. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82682. for (var i = 0; i < 10; ++i) {
  82683. this.data[i] += data[i];
  82684. }
  82685. };
  82686. QuadraticMatrix.prototype.add = function (matrix) {
  82687. var m = new QuadraticMatrix();
  82688. for (var i = 0; i < 10; ++i) {
  82689. m.data[i] = this.data[i] + matrix.data[i];
  82690. }
  82691. return m;
  82692. };
  82693. QuadraticMatrix.FromData = function (a, b, c, d) {
  82694. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82695. };
  82696. //returning an array to avoid garbage collection
  82697. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82698. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82699. };
  82700. return QuadraticMatrix;
  82701. }());
  82702. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82703. var Reference = /** @class */ (function () {
  82704. function Reference(vertexId, triangleId) {
  82705. this.vertexId = vertexId;
  82706. this.triangleId = triangleId;
  82707. }
  82708. return Reference;
  82709. }());
  82710. BABYLON.Reference = Reference;
  82711. /**
  82712. * An implementation of the Quadratic Error simplification algorithm.
  82713. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82714. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82715. * @author RaananW
  82716. */
  82717. var QuadraticErrorSimplification = /** @class */ (function () {
  82718. function QuadraticErrorSimplification(_mesh) {
  82719. this._mesh = _mesh;
  82720. this.syncIterations = 5000;
  82721. this.aggressiveness = 7;
  82722. this.decimationIterations = 100;
  82723. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82724. }
  82725. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82726. var _this = this;
  82727. this.initDecimatedMesh();
  82728. //iterating through the submeshes array, one after the other.
  82729. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82730. _this.initWithMesh(loop.index, function () {
  82731. _this.runDecimation(settings, loop.index, function () {
  82732. loop.executeNext();
  82733. });
  82734. }, settings.optimizeMesh);
  82735. }, function () {
  82736. setTimeout(function () {
  82737. successCallback(_this._reconstructedMesh);
  82738. }, 0);
  82739. });
  82740. };
  82741. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82742. var _this = this;
  82743. var targetCount = ~~(this.triangles.length * settings.quality);
  82744. var deletedTriangles = 0;
  82745. var triangleCount = this.triangles.length;
  82746. var iterationFunction = function (iteration, callback) {
  82747. setTimeout(function () {
  82748. if (iteration % 5 === 0) {
  82749. _this.updateMesh(iteration === 0);
  82750. }
  82751. for (var i = 0; i < _this.triangles.length; ++i) {
  82752. _this.triangles[i].isDirty = false;
  82753. }
  82754. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82755. var trianglesIterator = function (i) {
  82756. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82757. var t = _this.triangles[tIdx];
  82758. if (!t)
  82759. return;
  82760. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82761. return;
  82762. }
  82763. for (var j = 0; j < 3; ++j) {
  82764. if (t.error[j] < threshold) {
  82765. var deleted0 = [];
  82766. var deleted1 = [];
  82767. var v0 = t.vertices[j];
  82768. var v1 = t.vertices[(j + 1) % 3];
  82769. if (v0.isBorder || v1.isBorder)
  82770. continue;
  82771. var p = BABYLON.Vector3.Zero();
  82772. var n = BABYLON.Vector3.Zero();
  82773. var uv = BABYLON.Vector2.Zero();
  82774. var color = new BABYLON.Color4(0, 0, 0, 1);
  82775. _this.calculateError(v0, v1, p, n, uv, color);
  82776. var delTr = new Array();
  82777. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82778. continue;
  82779. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82780. continue;
  82781. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82782. continue;
  82783. var uniqueArray = new Array();
  82784. delTr.forEach(function (deletedT) {
  82785. if (uniqueArray.indexOf(deletedT) === -1) {
  82786. deletedT.deletePending = true;
  82787. uniqueArray.push(deletedT);
  82788. }
  82789. });
  82790. if (uniqueArray.length % 2 !== 0) {
  82791. continue;
  82792. }
  82793. v0.q = v1.q.add(v0.q);
  82794. v0.updatePosition(p);
  82795. var tStart = _this.references.length;
  82796. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82797. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82798. var tCount = _this.references.length - tStart;
  82799. if (tCount <= v0.triangleCount) {
  82800. if (tCount) {
  82801. for (var c = 0; c < tCount; c++) {
  82802. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82803. }
  82804. }
  82805. }
  82806. else {
  82807. v0.triangleStart = tStart;
  82808. }
  82809. v0.triangleCount = tCount;
  82810. break;
  82811. }
  82812. }
  82813. };
  82814. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82815. }, 0);
  82816. };
  82817. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82818. if (triangleCount - deletedTriangles <= targetCount)
  82819. loop.breakLoop();
  82820. else {
  82821. iterationFunction(loop.index, function () {
  82822. loop.executeNext();
  82823. });
  82824. }
  82825. }, function () {
  82826. setTimeout(function () {
  82827. //reconstruct this part of the mesh
  82828. _this.reconstructMesh(submeshIndex);
  82829. successCallback();
  82830. }, 0);
  82831. });
  82832. };
  82833. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82834. var _this = this;
  82835. this.vertices = [];
  82836. this.triangles = [];
  82837. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82838. var indices = this._mesh.getIndices();
  82839. var submesh = this._mesh.subMeshes[submeshIndex];
  82840. var findInVertices = function (positionToSearch) {
  82841. if (optimizeMesh) {
  82842. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82843. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82844. return _this.vertices[ii];
  82845. }
  82846. }
  82847. }
  82848. return null;
  82849. };
  82850. var vertexReferences = [];
  82851. var vertexInit = function (i) {
  82852. if (!positionData) {
  82853. return;
  82854. }
  82855. var offset = i + submesh.verticesStart;
  82856. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82857. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82858. vertex.originalOffsets.push(offset);
  82859. if (vertex.id === _this.vertices.length) {
  82860. _this.vertices.push(vertex);
  82861. }
  82862. vertexReferences.push(vertex.id);
  82863. };
  82864. //var totalVertices = mesh.getTotalVertices();
  82865. var totalVertices = submesh.verticesCount;
  82866. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82867. var indicesInit = function (i) {
  82868. if (!indices) {
  82869. return;
  82870. }
  82871. var offset = (submesh.indexStart / 3) + i;
  82872. var pos = (offset * 3);
  82873. var i0 = indices[pos + 0];
  82874. var i1 = indices[pos + 1];
  82875. var i2 = indices[pos + 2];
  82876. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82877. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82878. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82879. var triangle = new DecimationTriangle([v0, v1, v2]);
  82880. triangle.originalOffset = pos;
  82881. _this.triangles.push(triangle);
  82882. };
  82883. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82884. _this.init(callback);
  82885. });
  82886. });
  82887. };
  82888. QuadraticErrorSimplification.prototype.init = function (callback) {
  82889. var _this = this;
  82890. var triangleInit1 = function (i) {
  82891. var t = _this.triangles[i];
  82892. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82893. for (var j = 0; j < 3; j++) {
  82894. 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))));
  82895. }
  82896. };
  82897. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82898. var triangleInit2 = function (i) {
  82899. var t = _this.triangles[i];
  82900. for (var j = 0; j < 3; ++j) {
  82901. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82902. }
  82903. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82904. };
  82905. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82906. callback();
  82907. });
  82908. });
  82909. };
  82910. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82911. var newTriangles = [];
  82912. var i;
  82913. for (i = 0; i < this.vertices.length; ++i) {
  82914. this.vertices[i].triangleCount = 0;
  82915. }
  82916. var t;
  82917. var j;
  82918. for (i = 0; i < this.triangles.length; ++i) {
  82919. if (!this.triangles[i].deleted) {
  82920. t = this.triangles[i];
  82921. for (j = 0; j < 3; ++j) {
  82922. t.vertices[j].triangleCount = 1;
  82923. }
  82924. newTriangles.push(t);
  82925. }
  82926. }
  82927. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82928. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82929. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82930. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82931. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82932. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82933. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82934. var vertexCount = 0;
  82935. for (i = 0; i < this.vertices.length; ++i) {
  82936. var vertex = this.vertices[i];
  82937. vertex.id = vertexCount;
  82938. if (vertex.triangleCount) {
  82939. vertex.originalOffsets.forEach(function (originalOffset) {
  82940. if (!normalData) {
  82941. return;
  82942. }
  82943. newPositionData.push(vertex.position.x);
  82944. newPositionData.push(vertex.position.y);
  82945. newPositionData.push(vertex.position.z);
  82946. newNormalData.push(normalData[originalOffset * 3]);
  82947. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82948. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82949. if (uvs && uvs.length) {
  82950. newUVsData.push(uvs[(originalOffset * 2)]);
  82951. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82952. }
  82953. else if (colorsData && colorsData.length) {
  82954. newColorsData.push(colorsData[(originalOffset * 4)]);
  82955. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82956. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82957. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82958. }
  82959. ++vertexCount;
  82960. });
  82961. }
  82962. }
  82963. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82964. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82965. var submeshesArray = this._reconstructedMesh.subMeshes;
  82966. this._reconstructedMesh.subMeshes = [];
  82967. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82968. var originalIndices = this._mesh.getIndices();
  82969. for (i = 0; i < newTriangles.length; ++i) {
  82970. t = newTriangles[i]; //now get the new referencing point for each vertex
  82971. [0, 1, 2].forEach(function (idx) {
  82972. var id = originalIndices[t.originalOffset + idx];
  82973. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82974. if (offset < 0)
  82975. offset = 0;
  82976. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82977. });
  82978. }
  82979. //overwriting the old vertex buffers and indices.
  82980. this._reconstructedMesh.setIndices(newIndicesArray);
  82981. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82982. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82983. if (newUVsData.length > 0)
  82984. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82985. if (newColorsData.length > 0)
  82986. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82987. //create submesh
  82988. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82989. if (submeshIndex > 0) {
  82990. this._reconstructedMesh.subMeshes = [];
  82991. submeshesArray.forEach(function (submesh) {
  82992. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82993. });
  82994. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82995. }
  82996. };
  82997. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82998. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82999. this._reconstructedMesh.material = this._mesh.material;
  83000. this._reconstructedMesh.parent = this._mesh.parent;
  83001. this._reconstructedMesh.isVisible = false;
  83002. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83003. };
  83004. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83005. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83006. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83007. if (t.deleted)
  83008. continue;
  83009. var s = this.references[vertex1.triangleStart + i].vertexId;
  83010. var v1 = t.vertices[(s + 1) % 3];
  83011. var v2 = t.vertices[(s + 2) % 3];
  83012. if ((v1 === vertex2 || v2 === vertex2)) {
  83013. deletedArray[i] = true;
  83014. delTr.push(t);
  83015. continue;
  83016. }
  83017. var d1 = v1.position.subtract(point);
  83018. d1 = d1.normalize();
  83019. var d2 = v2.position.subtract(point);
  83020. d2 = d2.normalize();
  83021. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83022. return true;
  83023. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83024. deletedArray[i] = false;
  83025. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83026. return true;
  83027. }
  83028. return false;
  83029. };
  83030. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83031. var newDeleted = deletedTriangles;
  83032. for (var i = 0; i < vertex.triangleCount; ++i) {
  83033. var ref = this.references[vertex.triangleStart + i];
  83034. var t = this.triangles[ref.triangleId];
  83035. if (t.deleted)
  83036. continue;
  83037. if (deletedArray[i] && t.deletePending) {
  83038. t.deleted = true;
  83039. newDeleted++;
  83040. continue;
  83041. }
  83042. t.vertices[ref.vertexId] = origVertex;
  83043. t.isDirty = true;
  83044. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83045. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83046. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83047. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83048. this.references.push(ref);
  83049. }
  83050. return newDeleted;
  83051. };
  83052. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83053. for (var i = 0; i < this.vertices.length; ++i) {
  83054. var vCount = [];
  83055. var vId = [];
  83056. var v = this.vertices[i];
  83057. var j;
  83058. for (j = 0; j < v.triangleCount; ++j) {
  83059. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83060. for (var ii = 0; ii < 3; ii++) {
  83061. var ofs = 0;
  83062. var vv = triangle.vertices[ii];
  83063. while (ofs < vCount.length) {
  83064. if (vId[ofs] === vv.id)
  83065. break;
  83066. ++ofs;
  83067. }
  83068. if (ofs === vCount.length) {
  83069. vCount.push(1);
  83070. vId.push(vv.id);
  83071. }
  83072. else {
  83073. vCount[ofs]++;
  83074. }
  83075. }
  83076. }
  83077. for (j = 0; j < vCount.length; ++j) {
  83078. if (vCount[j] === 1) {
  83079. this.vertices[vId[j]].isBorder = true;
  83080. }
  83081. else {
  83082. this.vertices[vId[j]].isBorder = false;
  83083. }
  83084. }
  83085. }
  83086. };
  83087. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83088. if (identifyBorders === void 0) { identifyBorders = false; }
  83089. var i;
  83090. if (!identifyBorders) {
  83091. var newTrianglesVector = [];
  83092. for (i = 0; i < this.triangles.length; ++i) {
  83093. if (!this.triangles[i].deleted) {
  83094. newTrianglesVector.push(this.triangles[i]);
  83095. }
  83096. }
  83097. this.triangles = newTrianglesVector;
  83098. }
  83099. for (i = 0; i < this.vertices.length; ++i) {
  83100. this.vertices[i].triangleCount = 0;
  83101. this.vertices[i].triangleStart = 0;
  83102. }
  83103. var t;
  83104. var j;
  83105. var v;
  83106. for (i = 0; i < this.triangles.length; ++i) {
  83107. t = this.triangles[i];
  83108. for (j = 0; j < 3; ++j) {
  83109. v = t.vertices[j];
  83110. v.triangleCount++;
  83111. }
  83112. }
  83113. var tStart = 0;
  83114. for (i = 0; i < this.vertices.length; ++i) {
  83115. this.vertices[i].triangleStart = tStart;
  83116. tStart += this.vertices[i].triangleCount;
  83117. this.vertices[i].triangleCount = 0;
  83118. }
  83119. var newReferences = new Array(this.triangles.length * 3);
  83120. for (i = 0; i < this.triangles.length; ++i) {
  83121. t = this.triangles[i];
  83122. for (j = 0; j < 3; ++j) {
  83123. v = t.vertices[j];
  83124. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83125. v.triangleCount++;
  83126. }
  83127. }
  83128. this.references = newReferences;
  83129. if (identifyBorders) {
  83130. this.identifyBorder();
  83131. }
  83132. };
  83133. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83134. var x = point.x;
  83135. var y = point.y;
  83136. var z = point.z;
  83137. 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
  83138. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83139. };
  83140. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83141. var q = vertex1.q.add(vertex2.q);
  83142. var border = vertex1.isBorder && vertex2.isBorder;
  83143. var error = 0;
  83144. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83145. if (qDet !== 0 && !border) {
  83146. if (!pointResult) {
  83147. pointResult = BABYLON.Vector3.Zero();
  83148. }
  83149. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83150. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83151. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83152. error = this.vertexError(q, pointResult);
  83153. }
  83154. else {
  83155. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83156. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83157. var error1 = this.vertexError(q, vertex1.position);
  83158. var error2 = this.vertexError(q, vertex2.position);
  83159. var error3 = this.vertexError(q, p3);
  83160. error = Math.min(error1, error2, error3);
  83161. if (error === error1) {
  83162. if (pointResult) {
  83163. pointResult.copyFrom(vertex1.position);
  83164. }
  83165. }
  83166. else if (error === error2) {
  83167. if (pointResult) {
  83168. pointResult.copyFrom(vertex2.position);
  83169. }
  83170. }
  83171. else {
  83172. if (pointResult) {
  83173. pointResult.copyFrom(p3);
  83174. }
  83175. }
  83176. }
  83177. return error;
  83178. };
  83179. return QuadraticErrorSimplification;
  83180. }());
  83181. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83182. })(BABYLON || (BABYLON = {}));
  83183. //# sourceMappingURL=babylon.meshSimplification.js.map
  83184. var BABYLON;
  83185. (function (BABYLON) {
  83186. var MeshLODLevel = /** @class */ (function () {
  83187. function MeshLODLevel(distance, mesh) {
  83188. this.distance = distance;
  83189. this.mesh = mesh;
  83190. }
  83191. return MeshLODLevel;
  83192. }());
  83193. BABYLON.MeshLODLevel = MeshLODLevel;
  83194. })(BABYLON || (BABYLON = {}));
  83195. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83196. var BABYLON;
  83197. (function (BABYLON) {
  83198. /**
  83199. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83200. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83201. */
  83202. var SceneOptimization = /** @class */ (function () {
  83203. /**
  83204. * Creates the SceneOptimization object
  83205. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83206. * @param desc defines the description associated with the optimization
  83207. */
  83208. function SceneOptimization(
  83209. /**
  83210. * Defines the priority of this optimization (0 by default which means first in the list)
  83211. */
  83212. priority) {
  83213. if (priority === void 0) { priority = 0; }
  83214. this.priority = priority;
  83215. }
  83216. /**
  83217. * Gets a string describing the action executed by the current optimization
  83218. * @returns description string
  83219. */
  83220. SceneOptimization.prototype.getDescription = function () {
  83221. return "";
  83222. };
  83223. /**
  83224. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83225. * @param scene defines the current scene where to apply this optimization
  83226. * @param optimizer defines the current optimizer
  83227. * @returns true if everything that can be done was applied
  83228. */
  83229. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83230. return true;
  83231. };
  83232. ;
  83233. return SceneOptimization;
  83234. }());
  83235. BABYLON.SceneOptimization = SceneOptimization;
  83236. /**
  83237. * Defines an optimization used to reduce the size of render target textures
  83238. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83239. */
  83240. var TextureOptimization = /** @class */ (function (_super) {
  83241. __extends(TextureOptimization, _super);
  83242. /**
  83243. * Creates the TextureOptimization object
  83244. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83245. * @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
  83246. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83247. */
  83248. function TextureOptimization(
  83249. /**
  83250. * Defines the priority of this optimization (0 by default which means first in the list)
  83251. */
  83252. priority,
  83253. /**
  83254. * 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
  83255. */
  83256. maximumSize,
  83257. /**
  83258. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83259. */
  83260. step) {
  83261. if (priority === void 0) { priority = 0; }
  83262. if (maximumSize === void 0) { maximumSize = 1024; }
  83263. if (step === void 0) { step = 0.5; }
  83264. var _this = _super.call(this, priority) || this;
  83265. _this.priority = priority;
  83266. _this.maximumSize = maximumSize;
  83267. _this.step = step;
  83268. return _this;
  83269. }
  83270. /**
  83271. * Gets a string describing the action executed by the current optimization
  83272. * @returns description string
  83273. */
  83274. TextureOptimization.prototype.getDescription = function () {
  83275. return "Reducing render target texture size to " + this.maximumSize;
  83276. };
  83277. /**
  83278. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83279. * @param scene defines the current scene where to apply this optimization
  83280. * @param optimizer defines the current optimizer
  83281. * @returns true if everything that can be done was applied
  83282. */
  83283. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83284. var allDone = true;
  83285. for (var index = 0; index < scene.textures.length; index++) {
  83286. var texture = scene.textures[index];
  83287. if (!texture.canRescale || texture.getContext) {
  83288. continue;
  83289. }
  83290. var currentSize = texture.getSize();
  83291. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83292. if (maxDimension > this.maximumSize) {
  83293. texture.scale(this.step);
  83294. allDone = false;
  83295. }
  83296. }
  83297. return allDone;
  83298. };
  83299. return TextureOptimization;
  83300. }(SceneOptimization));
  83301. BABYLON.TextureOptimization = TextureOptimization;
  83302. /**
  83303. * Defines an optimization used to increase or decrease the rendering resolution
  83304. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83305. */
  83306. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83307. __extends(HardwareScalingOptimization, _super);
  83308. /**
  83309. * Creates the HardwareScalingOptimization object
  83310. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83311. * @param maximumScale defines the maximum scale to use (2 by default)
  83312. * @param step defines the step to use between two passes (0.5 by default)
  83313. */
  83314. function HardwareScalingOptimization(
  83315. /**
  83316. * Defines the priority of this optimization (0 by default which means first in the list)
  83317. */
  83318. priority,
  83319. /**
  83320. * Defines the maximum scale to use (2 by default)
  83321. */
  83322. maximumScale,
  83323. /**
  83324. * Defines the step to use between two passes (0.5 by default)
  83325. */
  83326. step) {
  83327. if (priority === void 0) { priority = 0; }
  83328. if (maximumScale === void 0) { maximumScale = 2; }
  83329. if (step === void 0) { step = 0.25; }
  83330. var _this = _super.call(this, priority) || this;
  83331. _this.priority = priority;
  83332. _this.maximumScale = maximumScale;
  83333. _this.step = step;
  83334. _this._currentScale = -1;
  83335. _this._directionOffset = 1;
  83336. return _this;
  83337. }
  83338. /**
  83339. * Gets a string describing the action executed by the current optimization
  83340. * @return description string
  83341. */
  83342. HardwareScalingOptimization.prototype.getDescription = function () {
  83343. return "Setting hardware scaling level to " + this._currentScale;
  83344. };
  83345. /**
  83346. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83347. * @param scene defines the current scene where to apply this optimization
  83348. * @param optimizer defines the current optimizer
  83349. * @returns true if everything that can be done was applied
  83350. */
  83351. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83352. if (this._currentScale === -1) {
  83353. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83354. if (this._currentScale > this.maximumScale) {
  83355. this._directionOffset = -1;
  83356. }
  83357. }
  83358. this._currentScale += this._directionOffset * this.step;
  83359. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83360. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83361. };
  83362. ;
  83363. return HardwareScalingOptimization;
  83364. }(SceneOptimization));
  83365. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83366. /**
  83367. * Defines an optimization used to remove shadows
  83368. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83369. */
  83370. var ShadowsOptimization = /** @class */ (function (_super) {
  83371. __extends(ShadowsOptimization, _super);
  83372. function ShadowsOptimization() {
  83373. return _super !== null && _super.apply(this, arguments) || this;
  83374. }
  83375. /**
  83376. * Gets a string describing the action executed by the current optimization
  83377. * @return description string
  83378. */
  83379. ShadowsOptimization.prototype.getDescription = function () {
  83380. return "Turning shadows on/off";
  83381. };
  83382. /**
  83383. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83384. * @param scene defines the current scene where to apply this optimization
  83385. * @param optimizer defines the current optimizer
  83386. * @returns true if everything that can be done was applied
  83387. */
  83388. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83389. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83390. return true;
  83391. };
  83392. ;
  83393. return ShadowsOptimization;
  83394. }(SceneOptimization));
  83395. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83396. /**
  83397. * Defines an optimization used to turn post-processes off
  83398. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83399. */
  83400. var PostProcessesOptimization = /** @class */ (function (_super) {
  83401. __extends(PostProcessesOptimization, _super);
  83402. function PostProcessesOptimization() {
  83403. return _super !== null && _super.apply(this, arguments) || this;
  83404. }
  83405. /**
  83406. * Gets a string describing the action executed by the current optimization
  83407. * @return description string
  83408. */
  83409. PostProcessesOptimization.prototype.getDescription = function () {
  83410. return "Turning post-processes on/off";
  83411. };
  83412. /**
  83413. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83414. * @param scene defines the current scene where to apply this optimization
  83415. * @param optimizer defines the current optimizer
  83416. * @returns true if everything that can be done was applied
  83417. */
  83418. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83419. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83420. return true;
  83421. };
  83422. ;
  83423. return PostProcessesOptimization;
  83424. }(SceneOptimization));
  83425. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83426. /**
  83427. * Defines an optimization used to turn lens flares off
  83428. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83429. */
  83430. var LensFlaresOptimization = /** @class */ (function (_super) {
  83431. __extends(LensFlaresOptimization, _super);
  83432. function LensFlaresOptimization() {
  83433. return _super !== null && _super.apply(this, arguments) || this;
  83434. }
  83435. /**
  83436. * Gets a string describing the action executed by the current optimization
  83437. * @return description string
  83438. */
  83439. LensFlaresOptimization.prototype.getDescription = function () {
  83440. return "Turning lens flares on/off";
  83441. };
  83442. /**
  83443. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83444. * @param scene defines the current scene where to apply this optimization
  83445. * @param optimizer defines the current optimizer
  83446. * @returns true if everything that can be done was applied
  83447. */
  83448. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83449. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83450. return true;
  83451. };
  83452. ;
  83453. return LensFlaresOptimization;
  83454. }(SceneOptimization));
  83455. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83456. /**
  83457. * Defines an optimization based on user defined callback.
  83458. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83459. */
  83460. var CustomOptimization = /** @class */ (function (_super) {
  83461. __extends(CustomOptimization, _super);
  83462. function CustomOptimization() {
  83463. return _super !== null && _super.apply(this, arguments) || this;
  83464. }
  83465. /**
  83466. * Gets a string describing the action executed by the current optimization
  83467. * @returns description string
  83468. */
  83469. CustomOptimization.prototype.getDescription = function () {
  83470. if (this.onGetDescription) {
  83471. return this.onGetDescription();
  83472. }
  83473. return "Running user defined callback";
  83474. };
  83475. /**
  83476. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83477. * @param scene defines the current scene where to apply this optimization
  83478. * @param optimizer defines the current optimizer
  83479. * @returns true if everything that can be done was applied
  83480. */
  83481. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83482. if (this.onApply) {
  83483. return this.onApply(scene, optimizer);
  83484. }
  83485. return true;
  83486. };
  83487. ;
  83488. return CustomOptimization;
  83489. }(SceneOptimization));
  83490. BABYLON.CustomOptimization = CustomOptimization;
  83491. /**
  83492. * Defines an optimization used to turn particles off
  83493. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83494. */
  83495. var ParticlesOptimization = /** @class */ (function (_super) {
  83496. __extends(ParticlesOptimization, _super);
  83497. function ParticlesOptimization() {
  83498. return _super !== null && _super.apply(this, arguments) || this;
  83499. }
  83500. /**
  83501. * Gets a string describing the action executed by the current optimization
  83502. * @return description string
  83503. */
  83504. ParticlesOptimization.prototype.getDescription = function () {
  83505. return "Turning particles on/off";
  83506. };
  83507. /**
  83508. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83509. * @param scene defines the current scene where to apply this optimization
  83510. * @param optimizer defines the current optimizer
  83511. * @returns true if everything that can be done was applied
  83512. */
  83513. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83514. scene.particlesEnabled = optimizer.isInImprovementMode;
  83515. return true;
  83516. };
  83517. ;
  83518. return ParticlesOptimization;
  83519. }(SceneOptimization));
  83520. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83521. /**
  83522. * Defines an optimization used to turn render targets off
  83523. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83524. */
  83525. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83526. __extends(RenderTargetsOptimization, _super);
  83527. function RenderTargetsOptimization() {
  83528. return _super !== null && _super.apply(this, arguments) || this;
  83529. }
  83530. /**
  83531. * Gets a string describing the action executed by the current optimization
  83532. * @return description string
  83533. */
  83534. RenderTargetsOptimization.prototype.getDescription = function () {
  83535. return "Turning render targets off";
  83536. };
  83537. /**
  83538. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83539. * @param scene defines the current scene where to apply this optimization
  83540. * @param optimizer defines the current optimizer
  83541. * @returns true if everything that can be done was applied
  83542. */
  83543. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83544. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83545. return true;
  83546. };
  83547. ;
  83548. return RenderTargetsOptimization;
  83549. }(SceneOptimization));
  83550. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83551. /**
  83552. * Defines an optimization used to merge meshes with compatible materials
  83553. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83554. */
  83555. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83556. __extends(MergeMeshesOptimization, _super);
  83557. function MergeMeshesOptimization() {
  83558. var _this = _super !== null && _super.apply(this, arguments) || this;
  83559. _this._canBeMerged = function (abstractMesh) {
  83560. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83561. return false;
  83562. }
  83563. var mesh = abstractMesh;
  83564. if (!mesh.isVisible || !mesh.isEnabled()) {
  83565. return false;
  83566. }
  83567. if (mesh.instances.length > 0) {
  83568. return false;
  83569. }
  83570. if (mesh.skeleton || mesh.hasLODLevels) {
  83571. return false;
  83572. }
  83573. if (mesh.parent) {
  83574. return false;
  83575. }
  83576. return true;
  83577. };
  83578. return _this;
  83579. }
  83580. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83581. /**
  83582. * Gets or sets a boolean which defines if optimization octree has to be updated
  83583. */
  83584. get: function () {
  83585. return MergeMeshesOptimization._UpdateSelectionTree;
  83586. },
  83587. /**
  83588. * Gets or sets a boolean which defines if optimization octree has to be updated
  83589. */
  83590. set: function (value) {
  83591. MergeMeshesOptimization._UpdateSelectionTree = value;
  83592. },
  83593. enumerable: true,
  83594. configurable: true
  83595. });
  83596. /**
  83597. * Gets a string describing the action executed by the current optimization
  83598. * @return description string
  83599. */
  83600. MergeMeshesOptimization.prototype.getDescription = function () {
  83601. return "Merging similar meshes together";
  83602. };
  83603. /**
  83604. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83605. * @param scene defines the current scene where to apply this optimization
  83606. * @param optimizer defines the current optimizer
  83607. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83608. * @returns true if everything that can be done was applied
  83609. */
  83610. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83611. var globalPool = scene.meshes.slice(0);
  83612. var globalLength = globalPool.length;
  83613. for (var index = 0; index < globalLength; index++) {
  83614. var currentPool = new Array();
  83615. var current = globalPool[index];
  83616. // Checks
  83617. if (!this._canBeMerged(current)) {
  83618. continue;
  83619. }
  83620. currentPool.push(current);
  83621. // Find compatible meshes
  83622. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83623. var otherMesh = globalPool[subIndex];
  83624. if (!this._canBeMerged(otherMesh)) {
  83625. continue;
  83626. }
  83627. if (otherMesh.material !== current.material) {
  83628. continue;
  83629. }
  83630. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83631. continue;
  83632. }
  83633. currentPool.push(otherMesh);
  83634. globalLength--;
  83635. globalPool.splice(subIndex, 1);
  83636. subIndex--;
  83637. }
  83638. if (currentPool.length < 2) {
  83639. continue;
  83640. }
  83641. // Merge meshes
  83642. BABYLON.Mesh.MergeMeshes(currentPool);
  83643. }
  83644. if (updateSelectionTree != undefined) {
  83645. if (updateSelectionTree) {
  83646. scene.createOrUpdateSelectionOctree();
  83647. }
  83648. }
  83649. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83650. scene.createOrUpdateSelectionOctree();
  83651. }
  83652. return true;
  83653. };
  83654. ;
  83655. MergeMeshesOptimization._UpdateSelectionTree = false;
  83656. return MergeMeshesOptimization;
  83657. }(SceneOptimization));
  83658. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83659. /**
  83660. * Defines a list of options used by SceneOptimizer
  83661. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83662. */
  83663. var SceneOptimizerOptions = /** @class */ (function () {
  83664. /**
  83665. * Creates a new list of options used by SceneOptimizer
  83666. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83667. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83668. */
  83669. function SceneOptimizerOptions(
  83670. /**
  83671. * Defines the target frame rate to reach (60 by default)
  83672. */
  83673. targetFrameRate,
  83674. /**
  83675. * Defines the interval between two checkes (2000ms by default)
  83676. */
  83677. trackerDuration) {
  83678. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83679. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83680. this.targetFrameRate = targetFrameRate;
  83681. this.trackerDuration = trackerDuration;
  83682. /**
  83683. * Gets the list of optimizations to apply
  83684. */
  83685. this.optimizations = new Array();
  83686. }
  83687. /**
  83688. * Add a new optimization
  83689. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83690. * @returns the current SceneOptimizerOptions
  83691. */
  83692. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83693. this.optimizations.push(optimization);
  83694. return this;
  83695. };
  83696. /**
  83697. * Add a new custom optimization
  83698. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83699. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83700. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83701. * @returns the current SceneOptimizerOptions
  83702. */
  83703. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83704. if (priority === void 0) { priority = 0; }
  83705. var optimization = new CustomOptimization(priority);
  83706. optimization.onApply = onApply;
  83707. optimization.onGetDescription = onGetDescription;
  83708. this.optimizations.push(optimization);
  83709. return this;
  83710. };
  83711. /**
  83712. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83713. * @param targetFrameRate defines the target frame rate (60 by default)
  83714. * @returns a SceneOptimizerOptions object
  83715. */
  83716. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83717. var result = new SceneOptimizerOptions(targetFrameRate);
  83718. var priority = 0;
  83719. result.addOptimization(new MergeMeshesOptimization(priority));
  83720. result.addOptimization(new ShadowsOptimization(priority));
  83721. result.addOptimization(new LensFlaresOptimization(priority));
  83722. // Next priority
  83723. priority++;
  83724. result.addOptimization(new PostProcessesOptimization(priority));
  83725. result.addOptimization(new ParticlesOptimization(priority));
  83726. // Next priority
  83727. priority++;
  83728. result.addOptimization(new TextureOptimization(priority, 1024));
  83729. return result;
  83730. };
  83731. /**
  83732. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83733. * @param targetFrameRate defines the target frame rate (60 by default)
  83734. * @returns a SceneOptimizerOptions object
  83735. */
  83736. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83737. var result = new SceneOptimizerOptions(targetFrameRate);
  83738. var priority = 0;
  83739. result.addOptimization(new MergeMeshesOptimization(priority));
  83740. result.addOptimization(new ShadowsOptimization(priority));
  83741. result.addOptimization(new LensFlaresOptimization(priority));
  83742. // Next priority
  83743. priority++;
  83744. result.addOptimization(new PostProcessesOptimization(priority));
  83745. result.addOptimization(new ParticlesOptimization(priority));
  83746. // Next priority
  83747. priority++;
  83748. result.addOptimization(new TextureOptimization(priority, 512));
  83749. // Next priority
  83750. priority++;
  83751. result.addOptimization(new RenderTargetsOptimization(priority));
  83752. // Next priority
  83753. priority++;
  83754. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83755. return result;
  83756. };
  83757. /**
  83758. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83759. * @param targetFrameRate defines the target frame rate (60 by default)
  83760. * @returns a SceneOptimizerOptions object
  83761. */
  83762. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83763. var result = new SceneOptimizerOptions(targetFrameRate);
  83764. var priority = 0;
  83765. result.addOptimization(new MergeMeshesOptimization(priority));
  83766. result.addOptimization(new ShadowsOptimization(priority));
  83767. result.addOptimization(new LensFlaresOptimization(priority));
  83768. // Next priority
  83769. priority++;
  83770. result.addOptimization(new PostProcessesOptimization(priority));
  83771. result.addOptimization(new ParticlesOptimization(priority));
  83772. // Next priority
  83773. priority++;
  83774. result.addOptimization(new TextureOptimization(priority, 256));
  83775. // Next priority
  83776. priority++;
  83777. result.addOptimization(new RenderTargetsOptimization(priority));
  83778. // Next priority
  83779. priority++;
  83780. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83781. return result;
  83782. };
  83783. return SceneOptimizerOptions;
  83784. }());
  83785. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83786. /**
  83787. * Class used to run optimizations in order to reach a target frame rate
  83788. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83789. */
  83790. var SceneOptimizer = /** @class */ (function () {
  83791. /**
  83792. * Creates a new SceneOptimizer
  83793. * @param scene defines the scene to work on
  83794. * @param options defines the options to use with the SceneOptimizer
  83795. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83796. * @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)
  83797. */
  83798. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83799. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83800. if (improvementMode === void 0) { improvementMode = false; }
  83801. var _this = this;
  83802. this._isRunning = false;
  83803. this._currentPriorityLevel = 0;
  83804. this._targetFrameRate = 60;
  83805. this._trackerDuration = 2000;
  83806. this._currentFrameRate = 0;
  83807. this._improvementMode = false;
  83808. /**
  83809. * Defines an observable called when the optimizer reaches the target frame rate
  83810. */
  83811. this.onSuccessObservable = new BABYLON.Observable();
  83812. /**
  83813. * Defines an observable called when the optimizer enables an optimization
  83814. */
  83815. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83816. /**
  83817. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83818. */
  83819. this.onFailureObservable = new BABYLON.Observable();
  83820. if (!options) {
  83821. this._options = new SceneOptimizerOptions();
  83822. }
  83823. else {
  83824. this._options = options;
  83825. }
  83826. if (this._options.targetFrameRate) {
  83827. this._targetFrameRate = this._options.targetFrameRate;
  83828. }
  83829. if (this._options.trackerDuration) {
  83830. this._trackerDuration = this._options.trackerDuration;
  83831. }
  83832. if (autoGeneratePriorities) {
  83833. var priority = 0;
  83834. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83835. var optim = _a[_i];
  83836. optim.priority = priority++;
  83837. }
  83838. }
  83839. this._improvementMode = improvementMode;
  83840. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83841. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83842. _this._sceneDisposeObserver = null;
  83843. _this.dispose();
  83844. });
  83845. }
  83846. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83847. /**
  83848. * Gets a boolean indicating if the optimizer is in improvement mode
  83849. */
  83850. get: function () {
  83851. return this._improvementMode;
  83852. },
  83853. enumerable: true,
  83854. configurable: true
  83855. });
  83856. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83857. /**
  83858. * Gets the current priority level (0 at start)
  83859. */
  83860. get: function () {
  83861. return this._currentPriorityLevel;
  83862. },
  83863. enumerable: true,
  83864. configurable: true
  83865. });
  83866. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83867. /**
  83868. * Gets the current frame rate checked by the SceneOptimizer
  83869. */
  83870. get: function () {
  83871. return this._currentFrameRate;
  83872. },
  83873. enumerable: true,
  83874. configurable: true
  83875. });
  83876. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83877. /**
  83878. * Gets or sets the current target frame rate (60 by default)
  83879. */
  83880. get: function () {
  83881. return this._targetFrameRate;
  83882. },
  83883. /**
  83884. * Gets or sets the current target frame rate (60 by default)
  83885. */
  83886. set: function (value) {
  83887. this._targetFrameRate = value;
  83888. },
  83889. enumerable: true,
  83890. configurable: true
  83891. });
  83892. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83893. /**
  83894. * Gets or sets the current interval between two checks (every 2000ms by default)
  83895. */
  83896. get: function () {
  83897. return this._trackerDuration;
  83898. },
  83899. /**
  83900. * Gets or sets the current interval between two checks (every 2000ms by default)
  83901. */
  83902. set: function (value) {
  83903. this._trackerDuration = value;
  83904. },
  83905. enumerable: true,
  83906. configurable: true
  83907. });
  83908. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83909. /**
  83910. * Gets the list of active optimizations
  83911. */
  83912. get: function () {
  83913. return this._options.optimizations;
  83914. },
  83915. enumerable: true,
  83916. configurable: true
  83917. });
  83918. /**
  83919. * Stops the current optimizer
  83920. */
  83921. SceneOptimizer.prototype.stop = function () {
  83922. this._isRunning = false;
  83923. };
  83924. /**
  83925. * Reset the optimizer to initial step (current priority level = 0)
  83926. */
  83927. SceneOptimizer.prototype.reset = function () {
  83928. this._currentPriorityLevel = 0;
  83929. };
  83930. /**
  83931. * Start the optimizer. By default it will try to reach a specific framerate
  83932. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83933. */
  83934. SceneOptimizer.prototype.start = function () {
  83935. var _this = this;
  83936. if (this._isRunning) {
  83937. return;
  83938. }
  83939. this._isRunning = true;
  83940. // Let's wait for the scene to be ready before running our check
  83941. this._scene.executeWhenReady(function () {
  83942. setTimeout(function () {
  83943. _this._checkCurrentState();
  83944. }, _this._trackerDuration);
  83945. });
  83946. };
  83947. SceneOptimizer.prototype._checkCurrentState = function () {
  83948. var _this = this;
  83949. if (!this._isRunning) {
  83950. return;
  83951. }
  83952. var scene = this._scene;
  83953. var options = this._options;
  83954. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83955. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83956. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83957. this._isRunning = false;
  83958. this.onSuccessObservable.notifyObservers(this);
  83959. return;
  83960. }
  83961. // Apply current level of optimizations
  83962. var allDone = true;
  83963. var noOptimizationApplied = true;
  83964. for (var index = 0; index < options.optimizations.length; index++) {
  83965. var optimization = options.optimizations[index];
  83966. if (optimization.priority === this._currentPriorityLevel) {
  83967. noOptimizationApplied = false;
  83968. allDone = allDone && optimization.apply(scene, this);
  83969. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83970. }
  83971. }
  83972. // If no optimization was applied, this is a failure :(
  83973. if (noOptimizationApplied) {
  83974. this._isRunning = false;
  83975. this.onFailureObservable.notifyObservers(this);
  83976. return;
  83977. }
  83978. // If all optimizations were done, move to next level
  83979. if (allDone) {
  83980. this._currentPriorityLevel++;
  83981. }
  83982. // Let's the system running for a specific amount of time before checking FPS
  83983. scene.executeWhenReady(function () {
  83984. setTimeout(function () {
  83985. _this._checkCurrentState();
  83986. }, _this._trackerDuration);
  83987. });
  83988. };
  83989. /**
  83990. * Release all resources
  83991. */
  83992. SceneOptimizer.prototype.dispose = function () {
  83993. this.stop();
  83994. this.onSuccessObservable.clear();
  83995. this.onFailureObservable.clear();
  83996. this.onNewOptimizationAppliedObservable.clear();
  83997. if (this._sceneDisposeObserver) {
  83998. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83999. }
  84000. };
  84001. /**
  84002. * Helper function to create a SceneOptimizer with one single line of code
  84003. * @param scene defines the scene to work on
  84004. * @param options defines the options to use with the SceneOptimizer
  84005. * @param onSuccess defines a callback to call on success
  84006. * @param onFailure defines a callback to call on failure
  84007. * @returns the new SceneOptimizer object
  84008. */
  84009. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84010. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84011. if (onSuccess) {
  84012. optimizer.onSuccessObservable.add(function () {
  84013. onSuccess();
  84014. });
  84015. }
  84016. if (onFailure) {
  84017. optimizer.onFailureObservable.add(function () {
  84018. onFailure();
  84019. });
  84020. }
  84021. optimizer.start();
  84022. return optimizer;
  84023. };
  84024. return SceneOptimizer;
  84025. }());
  84026. BABYLON.SceneOptimizer = SceneOptimizer;
  84027. })(BABYLON || (BABYLON = {}));
  84028. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84029. var BABYLON;
  84030. (function (BABYLON) {
  84031. var OutlineRenderer = /** @class */ (function () {
  84032. function OutlineRenderer(scene) {
  84033. this.zOffset = 1;
  84034. this._scene = scene;
  84035. }
  84036. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84037. var _this = this;
  84038. if (useOverlay === void 0) { useOverlay = false; }
  84039. var scene = this._scene;
  84040. var engine = this._scene.getEngine();
  84041. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84042. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84043. return;
  84044. }
  84045. var mesh = subMesh.getRenderingMesh();
  84046. var material = subMesh.getMaterial();
  84047. if (!material || !scene.activeCamera) {
  84048. return;
  84049. }
  84050. engine.enableEffect(this._effect);
  84051. // Logarithmic depth
  84052. if (material.useLogarithmicDepth) {
  84053. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84054. }
  84055. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84056. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84057. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84058. // Bones
  84059. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84060. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84061. }
  84062. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84063. // Alpha test
  84064. if (material && material.needAlphaTesting()) {
  84065. var alphaTexture = material.getAlphaTestTexture();
  84066. if (alphaTexture) {
  84067. this._effect.setTexture("diffuseSampler", alphaTexture);
  84068. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84069. }
  84070. }
  84071. engine.setZOffset(-this.zOffset);
  84072. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84073. engine.setZOffset(0);
  84074. };
  84075. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84076. var defines = [];
  84077. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84078. var mesh = subMesh.getMesh();
  84079. var material = subMesh.getMaterial();
  84080. if (material) {
  84081. // Alpha test
  84082. if (material.needAlphaTesting()) {
  84083. defines.push("#define ALPHATEST");
  84084. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84085. attribs.push(BABYLON.VertexBuffer.UVKind);
  84086. defines.push("#define UV1");
  84087. }
  84088. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84089. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84090. defines.push("#define UV2");
  84091. }
  84092. }
  84093. //Logarithmic depth
  84094. if (material.useLogarithmicDepth) {
  84095. defines.push("#define LOGARITHMICDEPTH");
  84096. }
  84097. }
  84098. // Bones
  84099. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84100. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84101. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84102. if (mesh.numBoneInfluencers > 4) {
  84103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84105. }
  84106. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84107. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84108. }
  84109. else {
  84110. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84111. }
  84112. // Instances
  84113. if (useInstances) {
  84114. defines.push("#define INSTANCES");
  84115. attribs.push("world0");
  84116. attribs.push("world1");
  84117. attribs.push("world2");
  84118. attribs.push("world3");
  84119. }
  84120. // Get correct effect
  84121. var join = defines.join("\n");
  84122. if (this._cachedDefines !== join) {
  84123. this._cachedDefines = join;
  84124. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84125. }
  84126. return this._effect.isReady();
  84127. };
  84128. return OutlineRenderer;
  84129. }());
  84130. BABYLON.OutlineRenderer = OutlineRenderer;
  84131. })(BABYLON || (BABYLON = {}));
  84132. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84133. var BABYLON;
  84134. (function (BABYLON) {
  84135. var FaceAdjacencies = /** @class */ (function () {
  84136. function FaceAdjacencies() {
  84137. this.edges = new Array();
  84138. this.edgesConnectedCount = 0;
  84139. }
  84140. return FaceAdjacencies;
  84141. }());
  84142. var EdgesRenderer = /** @class */ (function () {
  84143. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84144. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84145. if (epsilon === void 0) { epsilon = 0.95; }
  84146. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84147. this.edgesWidthScalerForOrthographic = 1000.0;
  84148. this.edgesWidthScalerForPerspective = 50.0;
  84149. this._linesPositions = new Array();
  84150. this._linesNormals = new Array();
  84151. this._linesIndices = new Array();
  84152. this._buffers = {};
  84153. this._checkVerticesInsteadOfIndices = false;
  84154. this._source = source;
  84155. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84156. this._epsilon = epsilon;
  84157. this._prepareRessources();
  84158. this._generateEdgesLines();
  84159. }
  84160. EdgesRenderer.prototype._prepareRessources = function () {
  84161. if (this._lineShader) {
  84162. return;
  84163. }
  84164. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84165. attributes: ["position", "normal"],
  84166. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84167. });
  84168. this._lineShader.disableDepthWrite = true;
  84169. this._lineShader.backFaceCulling = false;
  84170. };
  84171. EdgesRenderer.prototype._rebuild = function () {
  84172. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84173. if (buffer) {
  84174. buffer._rebuild();
  84175. }
  84176. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84177. if (buffer) {
  84178. buffer._rebuild();
  84179. }
  84180. var scene = this._source.getScene();
  84181. var engine = scene.getEngine();
  84182. this._ib = engine.createIndexBuffer(this._linesIndices);
  84183. };
  84184. EdgesRenderer.prototype.dispose = function () {
  84185. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84186. if (buffer) {
  84187. buffer.dispose();
  84188. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84189. }
  84190. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84191. if (buffer) {
  84192. buffer.dispose();
  84193. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84194. }
  84195. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84196. this._lineShader.dispose();
  84197. };
  84198. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84199. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84200. return 0;
  84201. }
  84202. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84203. return 1;
  84204. }
  84205. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84206. return 2;
  84207. }
  84208. return -1;
  84209. };
  84210. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84211. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84212. return 0;
  84213. }
  84214. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84215. return 1;
  84216. }
  84217. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84218. return 2;
  84219. }
  84220. return -1;
  84221. };
  84222. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84223. var needToCreateLine;
  84224. if (edge === undefined) {
  84225. needToCreateLine = true;
  84226. }
  84227. else {
  84228. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84229. needToCreateLine = dotProduct < this._epsilon;
  84230. }
  84231. if (needToCreateLine) {
  84232. var offset = this._linesPositions.length / 3;
  84233. var normal = p0.subtract(p1);
  84234. normal.normalize();
  84235. // Positions
  84236. this._linesPositions.push(p0.x);
  84237. this._linesPositions.push(p0.y);
  84238. this._linesPositions.push(p0.z);
  84239. this._linesPositions.push(p0.x);
  84240. this._linesPositions.push(p0.y);
  84241. this._linesPositions.push(p0.z);
  84242. this._linesPositions.push(p1.x);
  84243. this._linesPositions.push(p1.y);
  84244. this._linesPositions.push(p1.z);
  84245. this._linesPositions.push(p1.x);
  84246. this._linesPositions.push(p1.y);
  84247. this._linesPositions.push(p1.z);
  84248. // Normals
  84249. this._linesNormals.push(p1.x);
  84250. this._linesNormals.push(p1.y);
  84251. this._linesNormals.push(p1.z);
  84252. this._linesNormals.push(-1);
  84253. this._linesNormals.push(p1.x);
  84254. this._linesNormals.push(p1.y);
  84255. this._linesNormals.push(p1.z);
  84256. this._linesNormals.push(1);
  84257. this._linesNormals.push(p0.x);
  84258. this._linesNormals.push(p0.y);
  84259. this._linesNormals.push(p0.z);
  84260. this._linesNormals.push(-1);
  84261. this._linesNormals.push(p0.x);
  84262. this._linesNormals.push(p0.y);
  84263. this._linesNormals.push(p0.z);
  84264. this._linesNormals.push(1);
  84265. // Indices
  84266. this._linesIndices.push(offset);
  84267. this._linesIndices.push(offset + 1);
  84268. this._linesIndices.push(offset + 2);
  84269. this._linesIndices.push(offset);
  84270. this._linesIndices.push(offset + 2);
  84271. this._linesIndices.push(offset + 3);
  84272. }
  84273. };
  84274. EdgesRenderer.prototype._generateEdgesLines = function () {
  84275. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84276. var indices = this._source.getIndices();
  84277. if (!indices || !positions) {
  84278. return;
  84279. }
  84280. // First let's find adjacencies
  84281. var adjacencies = new Array();
  84282. var faceNormals = new Array();
  84283. var index;
  84284. var faceAdjacencies;
  84285. // Prepare faces
  84286. for (index = 0; index < indices.length; index += 3) {
  84287. faceAdjacencies = new FaceAdjacencies();
  84288. var p0Index = indices[index];
  84289. var p1Index = indices[index + 1];
  84290. var p2Index = indices[index + 2];
  84291. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84292. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84293. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84294. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84295. faceNormal.normalize();
  84296. faceNormals.push(faceNormal);
  84297. adjacencies.push(faceAdjacencies);
  84298. }
  84299. // Scan
  84300. for (index = 0; index < adjacencies.length; index++) {
  84301. faceAdjacencies = adjacencies[index];
  84302. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84303. var otherFaceAdjacencies = adjacencies[otherIndex];
  84304. if (faceAdjacencies.edgesConnectedCount === 3) {
  84305. break;
  84306. }
  84307. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84308. continue;
  84309. }
  84310. var otherP0 = indices[otherIndex * 3];
  84311. var otherP1 = indices[otherIndex * 3 + 1];
  84312. var otherP2 = indices[otherIndex * 3 + 2];
  84313. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84314. var otherEdgeIndex = 0;
  84315. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84316. continue;
  84317. }
  84318. switch (edgeIndex) {
  84319. case 0:
  84320. if (this._checkVerticesInsteadOfIndices) {
  84321. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84322. }
  84323. else {
  84324. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84325. }
  84326. break;
  84327. case 1:
  84328. if (this._checkVerticesInsteadOfIndices) {
  84329. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84330. }
  84331. else {
  84332. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84333. }
  84334. break;
  84335. case 2:
  84336. if (this._checkVerticesInsteadOfIndices) {
  84337. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84338. }
  84339. else {
  84340. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84341. }
  84342. break;
  84343. }
  84344. if (otherEdgeIndex === -1) {
  84345. continue;
  84346. }
  84347. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84348. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84349. faceAdjacencies.edgesConnectedCount++;
  84350. otherFaceAdjacencies.edgesConnectedCount++;
  84351. if (faceAdjacencies.edgesConnectedCount === 3) {
  84352. break;
  84353. }
  84354. }
  84355. }
  84356. }
  84357. // Create lines
  84358. for (index = 0; index < adjacencies.length; index++) {
  84359. // 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
  84360. var current = adjacencies[index];
  84361. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84362. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84363. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84364. }
  84365. // Merge into a single mesh
  84366. var engine = this._source.getScene().getEngine();
  84367. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84368. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84369. this._ib = engine.createIndexBuffer(this._linesIndices);
  84370. this._indicesCount = this._linesIndices.length;
  84371. };
  84372. EdgesRenderer.prototype.render = function () {
  84373. var scene = this._source.getScene();
  84374. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84375. return;
  84376. }
  84377. var engine = scene.getEngine();
  84378. this._lineShader._preBind();
  84379. // VBOs
  84380. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84381. scene.resetCachedMaterial();
  84382. this._lineShader.setColor4("color", this._source.edgesColor);
  84383. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84384. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84385. }
  84386. else {
  84387. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84388. }
  84389. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84390. this._lineShader.bind(this._source.getWorldMatrix());
  84391. // Draw order
  84392. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84393. this._lineShader.unbind();
  84394. engine.setDepthWrite(true);
  84395. };
  84396. return EdgesRenderer;
  84397. }());
  84398. BABYLON.EdgesRenderer = EdgesRenderer;
  84399. })(BABYLON || (BABYLON = {}));
  84400. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84401. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84402. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84403. s = arguments[i];
  84404. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84405. t[p] = s[p];
  84406. }
  84407. return t;
  84408. };
  84409. var BABYLON;
  84410. (function (BABYLON) {
  84411. /**
  84412. * The effect layer Helps adding post process effect blended with the main pass.
  84413. *
  84414. * This can be for instance use to generate glow or higlight effects on the scene.
  84415. *
  84416. * The effect layer class can not be used directly and is intented to inherited from to be
  84417. * customized per effects.
  84418. */
  84419. var EffectLayer = /** @class */ (function () {
  84420. /**
  84421. * Instantiates a new effect Layer and references it in the scene.
  84422. * @param name The name of the layer
  84423. * @param scene The scene to use the layer in
  84424. */
  84425. function EffectLayer(
  84426. /** The Friendly of the effect in the scene */
  84427. name, scene) {
  84428. this.name = name;
  84429. this._vertexBuffers = {};
  84430. this._maxSize = 0;
  84431. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84432. this._shouldRender = true;
  84433. this._postProcesses = [];
  84434. this._textures = [];
  84435. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84436. /**
  84437. * The clear color of the texture used to generate the glow map.
  84438. */
  84439. this.neutralColor = new BABYLON.Color4();
  84440. /**
  84441. * Specifies wether the highlight layer is enabled or not.
  84442. */
  84443. this.isEnabled = true;
  84444. /**
  84445. * An event triggered when the effect layer has been disposed.
  84446. */
  84447. this.onDisposeObservable = new BABYLON.Observable();
  84448. /**
  84449. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84450. */
  84451. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84452. /**
  84453. * An event triggered when the generated texture is being merged in the scene.
  84454. */
  84455. this.onBeforeComposeObservable = new BABYLON.Observable();
  84456. /**
  84457. * An event triggered when the generated texture has been merged in the scene.
  84458. */
  84459. this.onAfterComposeObservable = new BABYLON.Observable();
  84460. /**
  84461. * An event triggered when the efffect layer changes its size.
  84462. */
  84463. this.onSizeChangedObservable = new BABYLON.Observable();
  84464. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84465. this._engine = scene.getEngine();
  84466. this._maxSize = this._engine.getCaps().maxTextureSize;
  84467. this._scene.effectLayers.push(this);
  84468. // Generate Buffers
  84469. this._generateIndexBuffer();
  84470. this._genrateVertexBuffer();
  84471. }
  84472. Object.defineProperty(EffectLayer.prototype, "camera", {
  84473. /**
  84474. * Gets the camera attached to the layer.
  84475. */
  84476. get: function () {
  84477. return this._effectLayerOptions.camera;
  84478. },
  84479. enumerable: true,
  84480. configurable: true
  84481. });
  84482. /**
  84483. * Initializes the effect layer with the required options.
  84484. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84485. */
  84486. EffectLayer.prototype._init = function (options) {
  84487. // Adapt options
  84488. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84489. this._setMainTextureSize();
  84490. this._createMainTexture();
  84491. this._createTextureAndPostProcesses();
  84492. this._mergeEffect = this._createMergeEffect();
  84493. };
  84494. /**
  84495. * Generates the index buffer of the full screen quad blending to the main canvas.
  84496. */
  84497. EffectLayer.prototype._generateIndexBuffer = function () {
  84498. // Indices
  84499. var indices = [];
  84500. indices.push(0);
  84501. indices.push(1);
  84502. indices.push(2);
  84503. indices.push(0);
  84504. indices.push(2);
  84505. indices.push(3);
  84506. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84507. };
  84508. /**
  84509. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84510. */
  84511. EffectLayer.prototype._genrateVertexBuffer = function () {
  84512. // VBO
  84513. var vertices = [];
  84514. vertices.push(1, 1);
  84515. vertices.push(-1, 1);
  84516. vertices.push(-1, -1);
  84517. vertices.push(1, -1);
  84518. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84519. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84520. };
  84521. /**
  84522. * Sets the main texture desired size which is the closest power of two
  84523. * of the engine canvas size.
  84524. */
  84525. EffectLayer.prototype._setMainTextureSize = function () {
  84526. if (this._effectLayerOptions.mainTextureFixedSize) {
  84527. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84528. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84529. }
  84530. else {
  84531. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84532. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84533. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84534. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84535. }
  84536. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84537. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84538. };
  84539. /**
  84540. * Creates the main texture for the effect layer.
  84541. */
  84542. EffectLayer.prototype._createMainTexture = function () {
  84543. var _this = this;
  84544. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84545. width: this._mainTextureDesiredSize.width,
  84546. height: this._mainTextureDesiredSize.height
  84547. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84548. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84549. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84550. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84551. this._mainTexture.anisotropicFilteringLevel = 1;
  84552. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84553. this._mainTexture.renderParticles = false;
  84554. this._mainTexture.renderList = null;
  84555. this._mainTexture.ignoreCameraViewport = true;
  84556. // Custom render function
  84557. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84558. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84559. var index;
  84560. var engine = _this._scene.getEngine();
  84561. if (depthOnlySubMeshes.length) {
  84562. engine.setColorWrite(false);
  84563. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84564. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84565. }
  84566. engine.setColorWrite(true);
  84567. }
  84568. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84569. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84570. }
  84571. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84572. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84573. }
  84574. for (index = 0; index < transparentSubMeshes.length; index++) {
  84575. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84576. }
  84577. };
  84578. this._mainTexture.onClearObservable.add(function (engine) {
  84579. engine.clear(_this.neutralColor, true, true, true);
  84580. });
  84581. };
  84582. /**
  84583. * Checks for the readiness of the element composing the layer.
  84584. * @param subMesh the mesh to check for
  84585. * @param useInstances specify wether or not to use instances to render the mesh
  84586. * @param emissiveTexture the associated emissive texture used to generate the glow
  84587. * @return true if ready otherwise, false
  84588. */
  84589. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84590. var material = subMesh.getMaterial();
  84591. if (!material) {
  84592. return false;
  84593. }
  84594. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84595. return false;
  84596. }
  84597. var defines = [];
  84598. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84599. var mesh = subMesh.getMesh();
  84600. var uv1 = false;
  84601. var uv2 = false;
  84602. // Alpha test
  84603. if (material && material.needAlphaTesting()) {
  84604. var alphaTexture = material.getAlphaTestTexture();
  84605. if (alphaTexture) {
  84606. defines.push("#define ALPHATEST");
  84607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84608. alphaTexture.coordinatesIndex === 1) {
  84609. defines.push("#define DIFFUSEUV2");
  84610. uv2 = true;
  84611. }
  84612. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84613. defines.push("#define DIFFUSEUV1");
  84614. uv1 = true;
  84615. }
  84616. }
  84617. }
  84618. // Emissive
  84619. if (emissiveTexture) {
  84620. defines.push("#define EMISSIVE");
  84621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84622. emissiveTexture.coordinatesIndex === 1) {
  84623. defines.push("#define EMISSIVEUV2");
  84624. uv2 = true;
  84625. }
  84626. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84627. defines.push("#define EMISSIVEUV1");
  84628. uv1 = true;
  84629. }
  84630. }
  84631. if (uv1) {
  84632. attribs.push(BABYLON.VertexBuffer.UVKind);
  84633. defines.push("#define UV1");
  84634. }
  84635. if (uv2) {
  84636. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84637. defines.push("#define UV2");
  84638. }
  84639. // Bones
  84640. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84643. if (mesh.numBoneInfluencers > 4) {
  84644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84646. }
  84647. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84648. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84649. }
  84650. else {
  84651. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84652. }
  84653. // Instances
  84654. if (useInstances) {
  84655. defines.push("#define INSTANCES");
  84656. attribs.push("world0");
  84657. attribs.push("world1");
  84658. attribs.push("world2");
  84659. attribs.push("world3");
  84660. }
  84661. // Get correct effect
  84662. var join = defines.join("\n");
  84663. if (this._cachedDefines !== join) {
  84664. this._cachedDefines = join;
  84665. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84666. }
  84667. return this._effectLayerMapGenerationEffect.isReady();
  84668. };
  84669. /**
  84670. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84671. */
  84672. EffectLayer.prototype.render = function () {
  84673. var currentEffect = this._mergeEffect;
  84674. // Check
  84675. if (!currentEffect.isReady())
  84676. return;
  84677. for (var i = 0; i < this._postProcesses.length; i++) {
  84678. if (!this._postProcesses[i].isReady()) {
  84679. return;
  84680. }
  84681. }
  84682. var engine = this._scene.getEngine();
  84683. this.onBeforeComposeObservable.notifyObservers(this);
  84684. // Render
  84685. engine.enableEffect(currentEffect);
  84686. engine.setState(false);
  84687. // VBOs
  84688. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84689. // Cache
  84690. var previousAlphaMode = engine.getAlphaMode();
  84691. // Go Blend.
  84692. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84693. // Blends the map on the main canvas.
  84694. this._internalRender(currentEffect);
  84695. // Restore Alpha
  84696. engine.setAlphaMode(previousAlphaMode);
  84697. this.onAfterComposeObservable.notifyObservers(this);
  84698. // Handle size changes.
  84699. var size = this._mainTexture.getSize();
  84700. this._setMainTextureSize();
  84701. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84702. // Recreate RTT and post processes on size change.
  84703. this.onSizeChangedObservable.notifyObservers(this);
  84704. this._disposeTextureAndPostProcesses();
  84705. this._createMainTexture();
  84706. this._createTextureAndPostProcesses();
  84707. }
  84708. };
  84709. /**
  84710. * Determine if a given mesh will be used in the current effect.
  84711. * @param mesh mesh to test
  84712. * @returns true if the mesh will be used
  84713. */
  84714. EffectLayer.prototype.hasMesh = function (mesh) {
  84715. return true;
  84716. };
  84717. /**
  84718. * Returns true if the layer contains information to display, otherwise false.
  84719. * @returns true if the glow layer should be rendered
  84720. */
  84721. EffectLayer.prototype.shouldRender = function () {
  84722. return this.isEnabled && this._shouldRender;
  84723. };
  84724. /**
  84725. * Returns true if the mesh should render, otherwise false.
  84726. * @param mesh The mesh to render
  84727. * @returns true if it should render otherwise false
  84728. */
  84729. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84730. return true;
  84731. };
  84732. /**
  84733. * Returns true if the mesh should render, otherwise false.
  84734. * @param mesh The mesh to render
  84735. * @returns true if it should render otherwise false
  84736. */
  84737. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84738. return true;
  84739. };
  84740. /**
  84741. * Renders the submesh passed in parameter to the generation map.
  84742. */
  84743. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84744. var _this = this;
  84745. if (!this.shouldRender()) {
  84746. return;
  84747. }
  84748. var material = subMesh.getMaterial();
  84749. var mesh = subMesh.getRenderingMesh();
  84750. var scene = this._scene;
  84751. var engine = scene.getEngine();
  84752. if (!material) {
  84753. return;
  84754. }
  84755. // Do not block in blend mode.
  84756. if (material.needAlphaBlendingForMesh(mesh)) {
  84757. return;
  84758. }
  84759. // Culling
  84760. engine.setState(material.backFaceCulling);
  84761. // Managing instances
  84762. var batch = mesh._getInstancesRenderList(subMesh._id);
  84763. if (batch.mustReturn) {
  84764. return;
  84765. }
  84766. // Early Exit per mesh
  84767. if (!this._shouldRenderMesh(mesh)) {
  84768. return;
  84769. }
  84770. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84771. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84772. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84773. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84774. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84775. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84776. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84777. // Alpha test
  84778. if (material && material.needAlphaTesting()) {
  84779. var alphaTexture = material.getAlphaTestTexture();
  84780. if (alphaTexture) {
  84781. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84782. var textureMatrix = alphaTexture.getTextureMatrix();
  84783. if (textureMatrix) {
  84784. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84785. }
  84786. }
  84787. }
  84788. // Glow emissive only
  84789. if (this._emissiveTextureAndColor.texture) {
  84790. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84791. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84792. }
  84793. // Bones
  84794. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84795. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84796. }
  84797. // Draw
  84798. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84799. }
  84800. else {
  84801. // Need to reset refresh rate of the shadowMap
  84802. this._mainTexture.resetRefreshCounter();
  84803. }
  84804. };
  84805. /**
  84806. * Rebuild the required buffers.
  84807. * @ignore Internal use only.
  84808. */
  84809. EffectLayer.prototype._rebuild = function () {
  84810. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84811. if (vb) {
  84812. vb._rebuild();
  84813. }
  84814. this._generateIndexBuffer();
  84815. };
  84816. /**
  84817. * Dispose only the render target textures and post process.
  84818. */
  84819. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84820. this._mainTexture.dispose();
  84821. for (var i = 0; i < this._postProcesses.length; i++) {
  84822. if (this._postProcesses[i]) {
  84823. this._postProcesses[i].dispose();
  84824. }
  84825. }
  84826. this._postProcesses = [];
  84827. for (var i = 0; i < this._textures.length; i++) {
  84828. if (this._textures[i]) {
  84829. this._textures[i].dispose();
  84830. }
  84831. }
  84832. this._textures = [];
  84833. };
  84834. /**
  84835. * Dispose the highlight layer and free resources.
  84836. */
  84837. EffectLayer.prototype.dispose = function () {
  84838. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84839. if (vertexBuffer) {
  84840. vertexBuffer.dispose();
  84841. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84842. }
  84843. if (this._indexBuffer) {
  84844. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84845. this._indexBuffer = null;
  84846. }
  84847. // Clean textures and post processes
  84848. this._disposeTextureAndPostProcesses();
  84849. // Remove from scene
  84850. var index = this._scene.effectLayers.indexOf(this, 0);
  84851. if (index > -1) {
  84852. this._scene.effectLayers.splice(index, 1);
  84853. }
  84854. // Callback
  84855. this.onDisposeObservable.notifyObservers(this);
  84856. this.onDisposeObservable.clear();
  84857. this.onBeforeRenderMainTextureObservable.clear();
  84858. this.onBeforeComposeObservable.clear();
  84859. this.onAfterComposeObservable.clear();
  84860. this.onSizeChangedObservable.clear();
  84861. };
  84862. return EffectLayer;
  84863. }());
  84864. BABYLON.EffectLayer = EffectLayer;
  84865. })(BABYLON || (BABYLON = {}));
  84866. //# sourceMappingURL=babylon.effectLayer.js.map
  84867. var BABYLON;
  84868. (function (BABYLON) {
  84869. /**
  84870. * Special Glow Blur post process only blurring the alpha channel
  84871. * It enforces keeping the most luminous color in the color channel.
  84872. */
  84873. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84874. __extends(GlowBlurPostProcess, _super);
  84875. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84877. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84878. _this.direction = direction;
  84879. _this.kernel = kernel;
  84880. _this.onApplyObservable.add(function (effect) {
  84881. effect.setFloat2("screenSize", _this.width, _this.height);
  84882. effect.setVector2("direction", _this.direction);
  84883. effect.setFloat("blurWidth", _this.kernel);
  84884. });
  84885. return _this;
  84886. }
  84887. return GlowBlurPostProcess;
  84888. }(BABYLON.PostProcess));
  84889. /**
  84890. * The highlight layer Helps adding a glow effect around a mesh.
  84891. *
  84892. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84893. * glowy meshes to your scene.
  84894. *
  84895. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84896. */
  84897. var HighlightLayer = /** @class */ (function (_super) {
  84898. __extends(HighlightLayer, _super);
  84899. /**
  84900. * Instantiates a new highlight Layer and references it to the scene..
  84901. * @param name The name of the layer
  84902. * @param scene The scene to use the layer in
  84903. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84904. */
  84905. function HighlightLayer(name, scene, options) {
  84906. var _this = _super.call(this, name, scene) || this;
  84907. _this.name = name;
  84908. /**
  84909. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84910. */
  84911. _this.innerGlow = true;
  84912. /**
  84913. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84914. */
  84915. _this.outerGlow = true;
  84916. /**
  84917. * An event triggered when the highlight layer is being blurred.
  84918. */
  84919. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84920. /**
  84921. * An event triggered when the highlight layer has been blurred.
  84922. */
  84923. _this.onAfterBlurObservable = new BABYLON.Observable();
  84924. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84925. _this._meshes = {};
  84926. _this._excludedMeshes = {};
  84927. _this.neutralColor = HighlightLayer.NeutralColor;
  84928. // Warn on stencil
  84929. if (!_this._engine.isStencilEnable) {
  84930. 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 }");
  84931. }
  84932. // Adapt options
  84933. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84934. // Initialize the layer
  84935. _this._init({
  84936. alphaBlendingMode: _this._options.alphaBlendingMode,
  84937. camera: _this._options.camera,
  84938. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84939. mainTextureRatio: _this._options.mainTextureRatio
  84940. });
  84941. // Do not render as long as no meshes have been added
  84942. _this._shouldRender = false;
  84943. return _this;
  84944. }
  84945. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84946. /**
  84947. * Gets the horizontal size of the blur.
  84948. */
  84949. get: function () {
  84950. return this._horizontalBlurPostprocess.kernel;
  84951. },
  84952. /**
  84953. * Specifies the horizontal size of the blur.
  84954. */
  84955. set: function (value) {
  84956. this._horizontalBlurPostprocess.kernel = value;
  84957. },
  84958. enumerable: true,
  84959. configurable: true
  84960. });
  84961. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84962. /**
  84963. * Gets the vertical size of the blur.
  84964. */
  84965. get: function () {
  84966. return this._verticalBlurPostprocess.kernel;
  84967. },
  84968. /**
  84969. * Specifies the vertical size of the blur.
  84970. */
  84971. set: function (value) {
  84972. this._verticalBlurPostprocess.kernel = value;
  84973. },
  84974. enumerable: true,
  84975. configurable: true
  84976. });
  84977. /**
  84978. * Get the effect name of the layer.
  84979. * @return The effect name
  84980. */
  84981. HighlightLayer.prototype.getEffectName = function () {
  84982. return HighlightLayer.EffectName;
  84983. };
  84984. /**
  84985. * Create the merge effect. This is the shader use to blit the information back
  84986. * to the main canvas at the end of the scene rendering.
  84987. */
  84988. HighlightLayer.prototype._createMergeEffect = function () {
  84989. // Effect
  84990. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84991. };
  84992. /**
  84993. * Creates the render target textures and post processes used in the highlight layer.
  84994. */
  84995. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84996. var _this = this;
  84997. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84998. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84999. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85000. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85001. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85002. width: blurTextureWidth,
  85003. height: blurTextureHeight
  85004. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85005. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85006. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85007. this._blurTexture.anisotropicFilteringLevel = 16;
  85008. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85009. this._blurTexture.renderParticles = false;
  85010. this._blurTexture.ignoreCameraViewport = true;
  85011. this._textures = [this._blurTexture];
  85012. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85013. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85014. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85015. effect.setTexture("textureSampler", _this._mainTexture);
  85016. });
  85017. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85018. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85019. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85020. });
  85021. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85022. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85023. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85024. });
  85025. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85026. }
  85027. else {
  85028. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85029. width: blurTextureWidth,
  85030. height: blurTextureHeight
  85031. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85032. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85033. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85034. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85035. effect.setTexture("textureSampler", _this._mainTexture);
  85036. });
  85037. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85038. width: blurTextureWidth,
  85039. height: blurTextureHeight
  85040. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85041. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85042. }
  85043. this._mainTexture.onAfterUnbindObservable.add(function () {
  85044. _this.onBeforeBlurObservable.notifyObservers(_this);
  85045. var internalTexture = _this._blurTexture.getInternalTexture();
  85046. if (internalTexture) {
  85047. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85048. }
  85049. _this.onAfterBlurObservable.notifyObservers(_this);
  85050. });
  85051. // Prevent autoClear.
  85052. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85053. };
  85054. /**
  85055. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85056. */
  85057. HighlightLayer.prototype.needStencil = function () {
  85058. return true;
  85059. };
  85060. /**
  85061. * Checks for the readiness of the element composing the layer.
  85062. * @param subMesh the mesh to check for
  85063. * @param useInstances specify wether or not to use instances to render the mesh
  85064. * @param emissiveTexture the associated emissive texture used to generate the glow
  85065. * @return true if ready otherwise, false
  85066. */
  85067. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85068. var material = subMesh.getMaterial();
  85069. var mesh = subMesh.getRenderingMesh();
  85070. if (!material || !mesh || !this._meshes) {
  85071. return false;
  85072. }
  85073. var emissiveTexture = null;
  85074. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85075. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85076. emissiveTexture = material.emissiveTexture;
  85077. }
  85078. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85079. };
  85080. /**
  85081. * Implementation specific of rendering the generating effect on the main canvas.
  85082. * @param effect The effect used to render through
  85083. */
  85084. HighlightLayer.prototype._internalRender = function (effect) {
  85085. // Texture
  85086. effect.setTexture("textureSampler", this._blurTexture);
  85087. // Cache
  85088. var engine = this._engine;
  85089. var previousStencilBuffer = engine.getStencilBuffer();
  85090. var previousStencilFunction = engine.getStencilFunction();
  85091. var previousStencilMask = engine.getStencilMask();
  85092. var previousStencilOperationPass = engine.getStencilOperationPass();
  85093. var previousStencilOperationFail = engine.getStencilOperationFail();
  85094. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85095. var previousStencilReference = engine.getStencilFunctionReference();
  85096. // Stencil operations
  85097. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85098. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85099. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85100. // Draw order
  85101. engine.setStencilMask(0x00);
  85102. engine.setStencilBuffer(true);
  85103. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85104. // 2 passes inner outer
  85105. if (this.outerGlow) {
  85106. effect.setFloat("offset", 0);
  85107. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85108. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85109. }
  85110. if (this.innerGlow) {
  85111. effect.setFloat("offset", 1);
  85112. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85113. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85114. }
  85115. // Restore Cache
  85116. engine.setStencilFunction(previousStencilFunction);
  85117. engine.setStencilMask(previousStencilMask);
  85118. engine.setStencilBuffer(previousStencilBuffer);
  85119. engine.setStencilOperationPass(previousStencilOperationPass);
  85120. engine.setStencilOperationFail(previousStencilOperationFail);
  85121. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85122. engine.setStencilFunctionReference(previousStencilReference);
  85123. };
  85124. /**
  85125. * Returns true if the layer contains information to display, otherwise false.
  85126. */
  85127. HighlightLayer.prototype.shouldRender = function () {
  85128. if (_super.prototype.shouldRender.call(this)) {
  85129. return this._meshes ? true : false;
  85130. }
  85131. return false;
  85132. };
  85133. /**
  85134. * Returns true if the mesh should render, otherwise false.
  85135. * @param mesh The mesh to render
  85136. * @returns true if it should render otherwise false
  85137. */
  85138. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85139. // Excluded Mesh
  85140. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85141. return false;
  85142. }
  85143. ;
  85144. return true;
  85145. };
  85146. /**
  85147. * Sets the required values for both the emissive texture and and the main color.
  85148. */
  85149. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85150. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85151. if (highlightLayerMesh) {
  85152. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85153. }
  85154. else {
  85155. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85156. }
  85157. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85158. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85159. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85160. }
  85161. else {
  85162. this._emissiveTextureAndColor.texture = null;
  85163. }
  85164. };
  85165. /**
  85166. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85167. * @param mesh The mesh to exclude from the highlight layer
  85168. */
  85169. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85170. if (!this._excludedMeshes) {
  85171. return;
  85172. }
  85173. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85174. if (!meshExcluded) {
  85175. this._excludedMeshes[mesh.uniqueId] = {
  85176. mesh: mesh,
  85177. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85178. mesh.getEngine().setStencilBuffer(false);
  85179. }),
  85180. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85181. mesh.getEngine().setStencilBuffer(true);
  85182. }),
  85183. };
  85184. }
  85185. };
  85186. /**
  85187. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85188. * @param mesh The mesh to highlight
  85189. */
  85190. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85191. if (!this._excludedMeshes) {
  85192. return;
  85193. }
  85194. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85195. if (meshExcluded) {
  85196. if (meshExcluded.beforeRender) {
  85197. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85198. }
  85199. if (meshExcluded.afterRender) {
  85200. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85201. }
  85202. }
  85203. this._excludedMeshes[mesh.uniqueId] = null;
  85204. };
  85205. /**
  85206. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85207. * @param mesh mesh to test
  85208. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85209. */
  85210. HighlightLayer.prototype.hasMesh = function (mesh) {
  85211. if (!this._meshes) {
  85212. return false;
  85213. }
  85214. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85215. };
  85216. /**
  85217. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85218. * @param mesh The mesh to highlight
  85219. * @param color The color of the highlight
  85220. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85221. */
  85222. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85223. var _this = this;
  85224. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85225. if (!this._meshes) {
  85226. return;
  85227. }
  85228. var meshHighlight = this._meshes[mesh.uniqueId];
  85229. if (meshHighlight) {
  85230. meshHighlight.color = color;
  85231. }
  85232. else {
  85233. this._meshes[mesh.uniqueId] = {
  85234. mesh: mesh,
  85235. color: color,
  85236. // Lambda required for capture due to Observable this context
  85237. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85238. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85239. _this._defaultStencilReference(mesh);
  85240. }
  85241. else {
  85242. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85243. }
  85244. }),
  85245. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85246. glowEmissiveOnly: glowEmissiveOnly
  85247. };
  85248. }
  85249. this._shouldRender = true;
  85250. };
  85251. /**
  85252. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85253. * @param mesh The mesh to highlight
  85254. */
  85255. HighlightLayer.prototype.removeMesh = function (mesh) {
  85256. if (!this._meshes) {
  85257. return;
  85258. }
  85259. var meshHighlight = this._meshes[mesh.uniqueId];
  85260. if (meshHighlight) {
  85261. if (meshHighlight.observerHighlight) {
  85262. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85263. }
  85264. if (meshHighlight.observerDefault) {
  85265. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85266. }
  85267. delete this._meshes[mesh.uniqueId];
  85268. }
  85269. this._shouldRender = false;
  85270. for (var meshHighlightToCheck in this._meshes) {
  85271. if (this._meshes[meshHighlightToCheck]) {
  85272. this._shouldRender = true;
  85273. break;
  85274. }
  85275. }
  85276. };
  85277. /**
  85278. * Force the stencil to the normal expected value for none glowing parts
  85279. */
  85280. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85281. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85282. };
  85283. /**
  85284. * Free any resources and references associated to a mesh.
  85285. * Internal use
  85286. * @param mesh The mesh to free.
  85287. */
  85288. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85289. this.removeMesh(mesh);
  85290. this.removeExcludedMesh(mesh);
  85291. };
  85292. /**
  85293. * Dispose the highlight layer and free resources.
  85294. */
  85295. HighlightLayer.prototype.dispose = function () {
  85296. if (this._meshes) {
  85297. // Clean mesh references
  85298. for (var id in this._meshes) {
  85299. var meshHighlight = this._meshes[id];
  85300. if (meshHighlight && meshHighlight.mesh) {
  85301. if (meshHighlight.observerHighlight) {
  85302. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85303. }
  85304. if (meshHighlight.observerDefault) {
  85305. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85306. }
  85307. }
  85308. }
  85309. this._meshes = null;
  85310. }
  85311. if (this._excludedMeshes) {
  85312. for (var id in this._excludedMeshes) {
  85313. var meshHighlight = this._excludedMeshes[id];
  85314. if (meshHighlight) {
  85315. if (meshHighlight.beforeRender) {
  85316. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85317. }
  85318. if (meshHighlight.afterRender) {
  85319. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85320. }
  85321. }
  85322. }
  85323. this._excludedMeshes = null;
  85324. }
  85325. _super.prototype.dispose.call(this);
  85326. };
  85327. /**
  85328. * Effect Name of the highlight layer.
  85329. */
  85330. HighlightLayer.EffectName = "HighlightLayer";
  85331. /**
  85332. * The neutral color used during the preparation of the glow effect.
  85333. * This is black by default as the blend operation is a blend operation.
  85334. */
  85335. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85336. /**
  85337. * Stencil value used for glowing meshes.
  85338. */
  85339. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85340. /**
  85341. * Stencil value used for the other meshes in the scene.
  85342. */
  85343. HighlightLayer.NormalMeshStencilReference = 0x01;
  85344. return HighlightLayer;
  85345. }(BABYLON.EffectLayer));
  85346. BABYLON.HighlightLayer = HighlightLayer;
  85347. })(BABYLON || (BABYLON = {}));
  85348. //# sourceMappingURL=babylon.highlightLayer.js.map
  85349. var BABYLON;
  85350. (function (BABYLON) {
  85351. /**
  85352. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85353. *
  85354. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85355. * glowy meshes to your scene.
  85356. *
  85357. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85358. */
  85359. var GlowLayer = /** @class */ (function (_super) {
  85360. __extends(GlowLayer, _super);
  85361. /**
  85362. * Instantiates a new glow Layer and references it to the scene.
  85363. * @param name The name of the layer
  85364. * @param scene The scene to use the layer in
  85365. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85366. */
  85367. function GlowLayer(name, scene, options) {
  85368. var _this = _super.call(this, name, scene) || this;
  85369. _this.name = name;
  85370. _this._intensity = 1.0;
  85371. _this._includedOnlyMeshes = [];
  85372. _this._excludedMeshes = [];
  85373. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85374. // Adapt options
  85375. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85376. // Initialize the layer
  85377. _this._init({
  85378. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85379. camera: _this._options.camera,
  85380. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85381. mainTextureRatio: _this._options.mainTextureRatio
  85382. });
  85383. return _this;
  85384. }
  85385. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85386. /**
  85387. * Gets the kernel size of the blur.
  85388. */
  85389. get: function () {
  85390. return this._horizontalBlurPostprocess1.kernel;
  85391. },
  85392. /**
  85393. * Sets the kernel size of the blur.
  85394. */
  85395. set: function (value) {
  85396. this._horizontalBlurPostprocess1.kernel = value;
  85397. this._verticalBlurPostprocess1.kernel = value;
  85398. this._horizontalBlurPostprocess2.kernel = value;
  85399. this._verticalBlurPostprocess2.kernel = value;
  85400. },
  85401. enumerable: true,
  85402. configurable: true
  85403. });
  85404. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85405. /**
  85406. * Gets the glow intensity.
  85407. */
  85408. get: function () {
  85409. return this._intensity;
  85410. },
  85411. /**
  85412. * Sets the glow intensity.
  85413. */
  85414. set: function (value) {
  85415. this._intensity = value;
  85416. },
  85417. enumerable: true,
  85418. configurable: true
  85419. });
  85420. /**
  85421. * Get the effect name of the layer.
  85422. * @return The effect name
  85423. */
  85424. GlowLayer.prototype.getEffectName = function () {
  85425. return GlowLayer.EffectName;
  85426. };
  85427. /**
  85428. * Create the merge effect. This is the shader use to blit the information back
  85429. * to the main canvas at the end of the scene rendering.
  85430. */
  85431. GlowLayer.prototype._createMergeEffect = function () {
  85432. // Effect
  85433. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85434. };
  85435. /**
  85436. * Creates the render target textures and post processes used in the glow layer.
  85437. */
  85438. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85439. var _this = this;
  85440. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85441. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85442. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85443. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85444. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85445. width: blurTextureWidth,
  85446. height: blurTextureHeight
  85447. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85448. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85449. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85450. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85451. this._blurTexture1.renderParticles = false;
  85452. this._blurTexture1.ignoreCameraViewport = true;
  85453. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85454. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85455. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85456. width: blurTextureWidth2,
  85457. height: blurTextureHeight2
  85458. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85459. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85460. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85461. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85462. this._blurTexture2.renderParticles = false;
  85463. this._blurTexture2.ignoreCameraViewport = true;
  85464. this._textures = [this._blurTexture1, this._blurTexture2];
  85465. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85466. width: blurTextureWidth,
  85467. height: blurTextureHeight
  85468. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85469. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85470. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85471. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85472. effect.setTexture("textureSampler", _this._mainTexture);
  85473. });
  85474. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85475. width: blurTextureWidth,
  85476. height: blurTextureHeight
  85477. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85478. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85479. width: blurTextureWidth2,
  85480. height: blurTextureHeight2
  85481. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85482. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85483. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85484. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85485. effect.setTexture("textureSampler", _this._blurTexture1);
  85486. });
  85487. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85488. width: blurTextureWidth2,
  85489. height: blurTextureHeight2
  85490. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85491. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85492. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85493. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85494. this._mainTexture.samples = this._options.mainTextureSamples;
  85495. this._mainTexture.onAfterUnbindObservable.add(function () {
  85496. var internalTexture = _this._blurTexture1.getInternalTexture();
  85497. if (internalTexture) {
  85498. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85499. internalTexture = _this._blurTexture2.getInternalTexture();
  85500. if (internalTexture) {
  85501. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85502. }
  85503. }
  85504. });
  85505. // Prevent autoClear.
  85506. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85507. };
  85508. /**
  85509. * Checks for the readiness of the element composing the layer.
  85510. * @param subMesh the mesh to check for
  85511. * @param useInstances specify wether or not to use instances to render the mesh
  85512. * @param emissiveTexture the associated emissive texture used to generate the glow
  85513. * @return true if ready otherwise, false
  85514. */
  85515. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85516. var material = subMesh.getMaterial();
  85517. var mesh = subMesh.getRenderingMesh();
  85518. if (!material || !mesh) {
  85519. return false;
  85520. }
  85521. var emissiveTexture = material.emissiveTexture;
  85522. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85523. };
  85524. /**
  85525. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85526. */
  85527. GlowLayer.prototype.needStencil = function () {
  85528. return false;
  85529. };
  85530. /**
  85531. * Implementation specific of rendering the generating effect on the main canvas.
  85532. * @param effect The effect used to render through
  85533. */
  85534. GlowLayer.prototype._internalRender = function (effect) {
  85535. // Texture
  85536. effect.setTexture("textureSampler", this._blurTexture1);
  85537. effect.setTexture("textureSampler2", this._blurTexture2);
  85538. effect.setFloat("offset", this._intensity);
  85539. // Cache
  85540. var engine = this._engine;
  85541. var previousStencilBuffer = engine.getStencilBuffer();
  85542. // Draw order
  85543. engine.setStencilBuffer(false);
  85544. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85545. // Draw order
  85546. engine.setStencilBuffer(previousStencilBuffer);
  85547. };
  85548. /**
  85549. * Sets the required values for both the emissive texture and and the main color.
  85550. */
  85551. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85552. var textureLevel = 1.0;
  85553. if (this.customEmissiveTextureSelector) {
  85554. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85555. }
  85556. else {
  85557. if (material) {
  85558. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85559. if (this._emissiveTextureAndColor.texture) {
  85560. textureLevel = this._emissiveTextureAndColor.texture.level;
  85561. }
  85562. }
  85563. else {
  85564. this._emissiveTextureAndColor.texture = null;
  85565. }
  85566. }
  85567. if (this.customEmissiveColorSelector) {
  85568. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85569. }
  85570. else {
  85571. if (material.emissiveColor) {
  85572. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85573. }
  85574. else {
  85575. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85576. }
  85577. }
  85578. };
  85579. /**
  85580. * Returns true if the mesh should render, otherwise false.
  85581. * @param mesh The mesh to render
  85582. * @returns true if it should render otherwise false
  85583. */
  85584. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85585. return this.hasMesh(mesh);
  85586. };
  85587. /**
  85588. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85589. * @param mesh The mesh to exclude from the glow layer
  85590. */
  85591. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85592. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85593. this._excludedMeshes.push(mesh.uniqueId);
  85594. }
  85595. };
  85596. /**
  85597. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85598. * @param mesh The mesh to remove
  85599. */
  85600. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85601. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85602. if (index !== -1) {
  85603. this._excludedMeshes.splice(index, 1);
  85604. }
  85605. };
  85606. /**
  85607. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85608. * @param mesh The mesh to include in the glow layer
  85609. */
  85610. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85611. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85612. this._includedOnlyMeshes.push(mesh.uniqueId);
  85613. }
  85614. };
  85615. /**
  85616. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85617. * @param mesh The mesh to remove
  85618. */
  85619. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85620. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85621. if (index !== -1) {
  85622. this._includedOnlyMeshes.splice(index, 1);
  85623. }
  85624. };
  85625. /**
  85626. * Determine if a given mesh will be used in the glow layer
  85627. * @param mesh The mesh to test
  85628. * @returns true if the mesh will be highlighted by the current glow layer
  85629. */
  85630. GlowLayer.prototype.hasMesh = function (mesh) {
  85631. // Included Mesh
  85632. if (this._includedOnlyMeshes.length) {
  85633. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85634. }
  85635. ;
  85636. // Excluded Mesh
  85637. if (this._excludedMeshes.length) {
  85638. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85639. }
  85640. ;
  85641. return true;
  85642. };
  85643. /**
  85644. * Free any resources and references associated to a mesh.
  85645. * Internal use
  85646. * @param mesh The mesh to free.
  85647. */
  85648. GlowLayer.prototype._disposeMesh = function (mesh) {
  85649. this.removeIncludedOnlyMesh(mesh);
  85650. this.removeExcludedMesh(mesh);
  85651. };
  85652. /**
  85653. * Effect Name of the layer.
  85654. */
  85655. GlowLayer.EffectName = "GlowLayer";
  85656. /**
  85657. * The default blur kernel size used for the glow.
  85658. */
  85659. GlowLayer.DefaultBlurKernelSize = 32;
  85660. /**
  85661. * The default texture size ratio used for the glow.
  85662. */
  85663. GlowLayer.DefaultTextureRatio = 0.5;
  85664. return GlowLayer;
  85665. }(BABYLON.EffectLayer));
  85666. BABYLON.GlowLayer = GlowLayer;
  85667. })(BABYLON || (BABYLON = {}));
  85668. //# sourceMappingURL=babylon.glowLayer.js.map
  85669. var BABYLON;
  85670. (function (BABYLON) {
  85671. /**
  85672. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85673. */
  85674. var AssetTaskState;
  85675. (function (AssetTaskState) {
  85676. /**
  85677. * Initialization
  85678. */
  85679. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85680. /**
  85681. * Running
  85682. */
  85683. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85684. /**
  85685. * Done
  85686. */
  85687. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85688. /**
  85689. * Error
  85690. */
  85691. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85692. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85693. /**
  85694. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85695. */
  85696. var AbstractAssetTask = /** @class */ (function () {
  85697. /**
  85698. * Creates a new {BABYLON.AssetsManager}
  85699. * @param name defines the name of the task
  85700. */
  85701. function AbstractAssetTask(
  85702. /**
  85703. * Task name
  85704. */ name) {
  85705. this.name = name;
  85706. this._isCompleted = false;
  85707. this._taskState = AssetTaskState.INIT;
  85708. }
  85709. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85710. /**
  85711. * Get if the task is completed
  85712. */
  85713. get: function () {
  85714. return this._isCompleted;
  85715. },
  85716. enumerable: true,
  85717. configurable: true
  85718. });
  85719. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85720. /**
  85721. * Gets the current state of the task
  85722. */
  85723. get: function () {
  85724. return this._taskState;
  85725. },
  85726. enumerable: true,
  85727. configurable: true
  85728. });
  85729. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85730. /**
  85731. * Gets the current error object (if task is in error)
  85732. */
  85733. get: function () {
  85734. return this._errorObject;
  85735. },
  85736. enumerable: true,
  85737. configurable: true
  85738. });
  85739. /**
  85740. * Internal only
  85741. * @ignore
  85742. */
  85743. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85744. if (this._errorObject) {
  85745. return;
  85746. }
  85747. this._errorObject = {
  85748. message: message,
  85749. exception: exception
  85750. };
  85751. };
  85752. /**
  85753. * Execute the current task
  85754. * @param scene defines the scene where you want your assets to be loaded
  85755. * @param onSuccess is a callback called when the task is successfully executed
  85756. * @param onError is a callback called if an error occurs
  85757. */
  85758. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85759. var _this = this;
  85760. this._taskState = AssetTaskState.RUNNING;
  85761. this.runTask(scene, function () {
  85762. _this.onDoneCallback(onSuccess, onError);
  85763. }, function (msg, exception) {
  85764. _this.onErrorCallback(onError, msg, exception);
  85765. });
  85766. };
  85767. /**
  85768. * Execute the current task
  85769. * @param scene defines the scene where you want your assets to be loaded
  85770. * @param onSuccess is a callback called when the task is successfully executed
  85771. * @param onError is a callback called if an error occurs
  85772. */
  85773. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85774. throw new Error("runTask is not implemented");
  85775. };
  85776. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85777. this._taskState = AssetTaskState.ERROR;
  85778. this._errorObject = {
  85779. message: message,
  85780. exception: exception
  85781. };
  85782. if (this.onError) {
  85783. this.onError(this, message, exception);
  85784. }
  85785. onError();
  85786. };
  85787. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85788. try {
  85789. this._taskState = AssetTaskState.DONE;
  85790. this._isCompleted = true;
  85791. if (this.onSuccess) {
  85792. this.onSuccess(this);
  85793. }
  85794. onSuccess();
  85795. }
  85796. catch (e) {
  85797. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85798. }
  85799. };
  85800. return AbstractAssetTask;
  85801. }());
  85802. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85803. /**
  85804. * Class used to share progress information about assets loading
  85805. */
  85806. var AssetsProgressEvent = /** @class */ (function () {
  85807. /**
  85808. * Creates a {BABYLON.AssetsProgressEvent}
  85809. * @param remainingCount defines the number of remaining tasks to process
  85810. * @param totalCount defines the total number of tasks
  85811. * @param task defines the task that was just processed
  85812. */
  85813. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85814. this.remainingCount = remainingCount;
  85815. this.totalCount = totalCount;
  85816. this.task = task;
  85817. }
  85818. return AssetsProgressEvent;
  85819. }());
  85820. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85821. /**
  85822. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85823. */
  85824. var MeshAssetTask = /** @class */ (function (_super) {
  85825. __extends(MeshAssetTask, _super);
  85826. /**
  85827. * Creates a new {BABYLON.MeshAssetTask}
  85828. * @param name defines the name of the task
  85829. * @param meshesNames defines the list of mesh's names you want to load
  85830. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85831. * @param sceneFilename defines the filename of the scene to load from
  85832. */
  85833. function MeshAssetTask(
  85834. /**
  85835. * Defines the name of the task
  85836. */
  85837. name,
  85838. /**
  85839. * Defines the list of mesh's names you want to load
  85840. */
  85841. meshesNames,
  85842. /**
  85843. * Defines the root url to use as a base to load your meshes and associated resources
  85844. */
  85845. rootUrl,
  85846. /**
  85847. * Defines the filename of the scene to load from
  85848. */
  85849. sceneFilename) {
  85850. var _this = _super.call(this, name) || this;
  85851. _this.name = name;
  85852. _this.meshesNames = meshesNames;
  85853. _this.rootUrl = rootUrl;
  85854. _this.sceneFilename = sceneFilename;
  85855. return _this;
  85856. }
  85857. /**
  85858. * Execute the current task
  85859. * @param scene defines the scene where you want your assets to be loaded
  85860. * @param onSuccess is a callback called when the task is successfully executed
  85861. * @param onError is a callback called if an error occurs
  85862. */
  85863. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85864. var _this = this;
  85865. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85866. _this.loadedMeshes = meshes;
  85867. _this.loadedParticleSystems = particleSystems;
  85868. _this.loadedSkeletons = skeletons;
  85869. onSuccess();
  85870. }, null, function (scene, message, exception) {
  85871. onError(message, exception);
  85872. });
  85873. };
  85874. return MeshAssetTask;
  85875. }(AbstractAssetTask));
  85876. BABYLON.MeshAssetTask = MeshAssetTask;
  85877. /**
  85878. * Define a task used by {BABYLON.AssetsManager} to load text content
  85879. */
  85880. var TextFileAssetTask = /** @class */ (function (_super) {
  85881. __extends(TextFileAssetTask, _super);
  85882. /**
  85883. * Creates a new TextFileAssetTask object
  85884. * @param name defines the name of the task
  85885. * @param url defines the location of the file to load
  85886. */
  85887. function TextFileAssetTask(
  85888. /**
  85889. * Defines the name of the task
  85890. */
  85891. name,
  85892. /**
  85893. * Defines the location of the file to load
  85894. */
  85895. url) {
  85896. var _this = _super.call(this, name) || this;
  85897. _this.name = name;
  85898. _this.url = url;
  85899. return _this;
  85900. }
  85901. /**
  85902. * Execute the current task
  85903. * @param scene defines the scene where you want your assets to be loaded
  85904. * @param onSuccess is a callback called when the task is successfully executed
  85905. * @param onError is a callback called if an error occurs
  85906. */
  85907. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85908. var _this = this;
  85909. scene._loadFile(this.url, function (data) {
  85910. _this.text = data;
  85911. onSuccess();
  85912. }, undefined, false, false, function (request, exception) {
  85913. if (request) {
  85914. onError(request.status + " " + request.statusText, exception);
  85915. }
  85916. });
  85917. };
  85918. return TextFileAssetTask;
  85919. }(AbstractAssetTask));
  85920. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85921. /**
  85922. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85923. */
  85924. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85925. __extends(BinaryFileAssetTask, _super);
  85926. /**
  85927. * Creates a new BinaryFileAssetTask object
  85928. * @param name defines the name of the new task
  85929. * @param url defines the location of the file to load
  85930. */
  85931. function BinaryFileAssetTask(
  85932. /**
  85933. * Defines the name of the task
  85934. */
  85935. name,
  85936. /**
  85937. * Defines the location of the file to load
  85938. */
  85939. url) {
  85940. var _this = _super.call(this, name) || this;
  85941. _this.name = name;
  85942. _this.url = url;
  85943. return _this;
  85944. }
  85945. /**
  85946. * Execute the current task
  85947. * @param scene defines the scene where you want your assets to be loaded
  85948. * @param onSuccess is a callback called when the task is successfully executed
  85949. * @param onError is a callback called if an error occurs
  85950. */
  85951. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85952. var _this = this;
  85953. scene._loadFile(this.url, function (data) {
  85954. _this.data = data;
  85955. onSuccess();
  85956. }, undefined, true, true, function (request, exception) {
  85957. if (request) {
  85958. onError(request.status + " " + request.statusText, exception);
  85959. }
  85960. });
  85961. };
  85962. return BinaryFileAssetTask;
  85963. }(AbstractAssetTask));
  85964. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85965. /**
  85966. * Define a task used by {BABYLON.AssetsManager} to load images
  85967. */
  85968. var ImageAssetTask = /** @class */ (function (_super) {
  85969. __extends(ImageAssetTask, _super);
  85970. /**
  85971. * Creates a new ImageAssetTask
  85972. * @param name defines the name of the task
  85973. * @param url defines the location of the image to load
  85974. */
  85975. function ImageAssetTask(
  85976. /**
  85977. * Defines the name of the task
  85978. */
  85979. name,
  85980. /**
  85981. * Defines the location of the image to load
  85982. */
  85983. url) {
  85984. var _this = _super.call(this, name) || this;
  85985. _this.name = name;
  85986. _this.url = url;
  85987. return _this;
  85988. }
  85989. /**
  85990. * Execute the current task
  85991. * @param scene defines the scene where you want your assets to be loaded
  85992. * @param onSuccess is a callback called when the task is successfully executed
  85993. * @param onError is a callback called if an error occurs
  85994. */
  85995. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85996. var _this = this;
  85997. var img = new Image();
  85998. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85999. img.onload = function () {
  86000. _this.image = img;
  86001. onSuccess();
  86002. };
  86003. img.onerror = function (err) {
  86004. onError("Error loading image", err);
  86005. };
  86006. img.src = this.url;
  86007. };
  86008. return ImageAssetTask;
  86009. }(AbstractAssetTask));
  86010. BABYLON.ImageAssetTask = ImageAssetTask;
  86011. /**
  86012. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86013. */
  86014. var TextureAssetTask = /** @class */ (function (_super) {
  86015. __extends(TextureAssetTask, _super);
  86016. /**
  86017. * Creates a new TextureAssetTask object
  86018. * @param name defines the name of the task
  86019. * @param url defines the location of the file to load
  86020. * @param noMipmap defines if mipmap should not be generated (default is false)
  86021. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86022. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86023. */
  86024. function TextureAssetTask(
  86025. /**
  86026. * Defines the name of the task
  86027. */
  86028. name,
  86029. /**
  86030. * Defines the location of the file to load
  86031. */
  86032. url,
  86033. /**
  86034. * Defines if mipmap should not be generated (default is false)
  86035. */
  86036. noMipmap,
  86037. /**
  86038. * Defines if texture must be inverted on Y axis (default is false)
  86039. */
  86040. invertY,
  86041. /**
  86042. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86043. */
  86044. samplingMode) {
  86045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86046. var _this = _super.call(this, name) || this;
  86047. _this.name = name;
  86048. _this.url = url;
  86049. _this.noMipmap = noMipmap;
  86050. _this.invertY = invertY;
  86051. _this.samplingMode = samplingMode;
  86052. return _this;
  86053. }
  86054. /**
  86055. * Execute the current task
  86056. * @param scene defines the scene where you want your assets to be loaded
  86057. * @param onSuccess is a callback called when the task is successfully executed
  86058. * @param onError is a callback called if an error occurs
  86059. */
  86060. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86061. var onload = function () {
  86062. onSuccess();
  86063. };
  86064. var onerror = function (message, exception) {
  86065. onError(message, exception);
  86066. };
  86067. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86068. };
  86069. return TextureAssetTask;
  86070. }(AbstractAssetTask));
  86071. BABYLON.TextureAssetTask = TextureAssetTask;
  86072. /**
  86073. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86074. */
  86075. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86076. __extends(CubeTextureAssetTask, _super);
  86077. /**
  86078. * Creates a new CubeTextureAssetTask
  86079. * @param name defines the name of the task
  86080. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86081. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86082. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86083. * @param files defines the explicit list of files (undefined by default)
  86084. */
  86085. function CubeTextureAssetTask(
  86086. /**
  86087. * Defines the name of the task
  86088. */
  86089. name,
  86090. /**
  86091. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86092. */
  86093. url,
  86094. /**
  86095. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86096. */
  86097. extensions,
  86098. /**
  86099. * Defines if mipmaps should not be generated (default is false)
  86100. */
  86101. noMipmap,
  86102. /**
  86103. * Defines the explicit list of files (undefined by default)
  86104. */
  86105. files) {
  86106. var _this = _super.call(this, name) || this;
  86107. _this.name = name;
  86108. _this.url = url;
  86109. _this.extensions = extensions;
  86110. _this.noMipmap = noMipmap;
  86111. _this.files = files;
  86112. return _this;
  86113. }
  86114. /**
  86115. * Execute the current task
  86116. * @param scene defines the scene where you want your assets to be loaded
  86117. * @param onSuccess is a callback called when the task is successfully executed
  86118. * @param onError is a callback called if an error occurs
  86119. */
  86120. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86121. var onload = function () {
  86122. onSuccess();
  86123. };
  86124. var onerror = function (message, exception) {
  86125. onError(message, exception);
  86126. };
  86127. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86128. };
  86129. return CubeTextureAssetTask;
  86130. }(AbstractAssetTask));
  86131. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86132. /**
  86133. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86134. */
  86135. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86136. __extends(HDRCubeTextureAssetTask, _super);
  86137. /**
  86138. * Creates a new HDRCubeTextureAssetTask object
  86139. * @param name defines the name of the task
  86140. * @param url defines the location of the file to load
  86141. * @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.
  86142. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86143. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86144. * @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)
  86145. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86146. */
  86147. function HDRCubeTextureAssetTask(
  86148. /**
  86149. * Defines the name of the task
  86150. */
  86151. name,
  86152. /**
  86153. * Defines the location of the file to load
  86154. */
  86155. url,
  86156. /**
  86157. * 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.
  86158. */
  86159. size,
  86160. /**
  86161. * Defines if mipmaps should not be generated (default is false)
  86162. */
  86163. noMipmap,
  86164. /**
  86165. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86166. */
  86167. generateHarmonics,
  86168. /**
  86169. * 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)
  86170. */
  86171. useInGammaSpace,
  86172. /**
  86173. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86174. */
  86175. usePMREMGenerator) {
  86176. if (noMipmap === void 0) { noMipmap = false; }
  86177. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86178. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86179. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86180. var _this = _super.call(this, name) || this;
  86181. _this.name = name;
  86182. _this.url = url;
  86183. _this.size = size;
  86184. _this.noMipmap = noMipmap;
  86185. _this.generateHarmonics = generateHarmonics;
  86186. _this.useInGammaSpace = useInGammaSpace;
  86187. _this.usePMREMGenerator = usePMREMGenerator;
  86188. return _this;
  86189. }
  86190. /**
  86191. * Execute the current task
  86192. * @param scene defines the scene where you want your assets to be loaded
  86193. * @param onSuccess is a callback called when the task is successfully executed
  86194. * @param onError is a callback called if an error occurs
  86195. */
  86196. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86197. var onload = function () {
  86198. onSuccess();
  86199. };
  86200. var onerror = function (message, exception) {
  86201. onError(message, exception);
  86202. };
  86203. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86204. };
  86205. return HDRCubeTextureAssetTask;
  86206. }(AbstractAssetTask));
  86207. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86208. /**
  86209. * This class can be used to easily import assets into a scene
  86210. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86211. */
  86212. var AssetsManager = /** @class */ (function () {
  86213. /**
  86214. * Creates a new AssetsManager
  86215. * @param scene defines the scene to work on
  86216. */
  86217. function AssetsManager(scene) {
  86218. this._isLoading = false;
  86219. this._tasks = new Array();
  86220. this._waitingTasksCount = 0;
  86221. this._totalTasksCount = 0;
  86222. /**
  86223. * Observable called when all tasks are processed
  86224. */
  86225. this.onTaskSuccessObservable = new BABYLON.Observable();
  86226. /**
  86227. * Observable called when a task had an error
  86228. */
  86229. this.onTaskErrorObservable = new BABYLON.Observable();
  86230. /**
  86231. * Observable called when a task is successful
  86232. */
  86233. this.onTasksDoneObservable = new BABYLON.Observable();
  86234. /**
  86235. * Observable called when a task is done (whatever the result is)
  86236. */
  86237. this.onProgressObservable = new BABYLON.Observable();
  86238. /**
  86239. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86240. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86241. */
  86242. this.useDefaultLoadingScreen = true;
  86243. this._scene = scene;
  86244. }
  86245. /**
  86246. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86247. * @param taskName defines the name of the new task
  86248. * @param meshesNames defines the name of meshes to load
  86249. * @param rootUrl defines the root url to use to locate files
  86250. * @param sceneFilename defines the filename of the scene file
  86251. * @returns a new {BABYLON.MeshAssetTask} object
  86252. */
  86253. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86254. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86255. this._tasks.push(task);
  86256. return task;
  86257. };
  86258. /**
  86259. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86260. * @param taskName defines the name of the new task
  86261. * @param url defines the url of the file to load
  86262. * @returns a new {BABYLON.TextFileAssetTask} object
  86263. */
  86264. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86265. var task = new TextFileAssetTask(taskName, url);
  86266. this._tasks.push(task);
  86267. return task;
  86268. };
  86269. /**
  86270. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86271. * @param taskName defines the name of the new task
  86272. * @param url defines the url of the file to load
  86273. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86274. */
  86275. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86276. var task = new BinaryFileAssetTask(taskName, url);
  86277. this._tasks.push(task);
  86278. return task;
  86279. };
  86280. /**
  86281. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86282. * @param taskName defines the name of the new task
  86283. * @param url defines the url of the file to load
  86284. * @returns a new {BABYLON.ImageAssetTask} object
  86285. */
  86286. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86287. var task = new ImageAssetTask(taskName, url);
  86288. this._tasks.push(task);
  86289. return task;
  86290. };
  86291. /**
  86292. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86293. * @param taskName defines the name of the new task
  86294. * @param url defines the url of the file to load
  86295. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86296. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86297. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86298. * @returns a new {BABYLON.TextureAssetTask} object
  86299. */
  86300. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86302. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86303. this._tasks.push(task);
  86304. return task;
  86305. };
  86306. /**
  86307. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86308. * @param taskName defines the name of the new task
  86309. * @param url defines the url of the file to load
  86310. * @param extensions defines the extension to use to load the cube map (can be null)
  86311. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86312. * @param files defines the list of files to load (can be null)
  86313. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86314. */
  86315. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86316. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86317. this._tasks.push(task);
  86318. return task;
  86319. };
  86320. /**
  86321. *
  86322. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86323. * @param taskName defines the name of the new task
  86324. * @param url defines the url of the file to load
  86325. * @param size defines the size you want for the cubemap (can be null)
  86326. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86327. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86328. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86329. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86330. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86331. */
  86332. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86333. if (noMipmap === void 0) { noMipmap = false; }
  86334. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86335. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86336. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86337. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86338. this._tasks.push(task);
  86339. return task;
  86340. };
  86341. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86342. var _this = this;
  86343. this._waitingTasksCount--;
  86344. try {
  86345. if (task.taskState === AssetTaskState.DONE) {
  86346. // Let's remove successfull tasks
  86347. BABYLON.Tools.SetImmediate(function () {
  86348. var index = _this._tasks.indexOf(task);
  86349. if (index > -1) {
  86350. _this._tasks.splice(index, 1);
  86351. }
  86352. });
  86353. }
  86354. if (this.onProgress) {
  86355. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86356. }
  86357. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86358. }
  86359. catch (e) {
  86360. BABYLON.Tools.Error("Error running progress callbacks.");
  86361. console.log(e);
  86362. }
  86363. if (this._waitingTasksCount === 0) {
  86364. try {
  86365. if (this.onFinish) {
  86366. this.onFinish(this._tasks);
  86367. }
  86368. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86369. }
  86370. catch (e) {
  86371. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86372. console.log(e);
  86373. }
  86374. this._isLoading = false;
  86375. this._scene.getEngine().hideLoadingUI();
  86376. }
  86377. };
  86378. AssetsManager.prototype._runTask = function (task) {
  86379. var _this = this;
  86380. var done = function () {
  86381. try {
  86382. if (_this.onTaskSuccess) {
  86383. _this.onTaskSuccess(task);
  86384. }
  86385. _this.onTaskSuccessObservable.notifyObservers(task);
  86386. _this._decreaseWaitingTasksCount(task);
  86387. }
  86388. catch (e) {
  86389. error("Error executing task success callbacks", e);
  86390. }
  86391. };
  86392. var error = function (message, exception) {
  86393. task._setErrorObject(message, exception);
  86394. if (_this.onTaskError) {
  86395. _this.onTaskError(task);
  86396. }
  86397. _this.onTaskErrorObservable.notifyObservers(task);
  86398. _this._decreaseWaitingTasksCount(task);
  86399. };
  86400. task.run(this._scene, done, error);
  86401. };
  86402. /**
  86403. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86404. * @return the current instance of the {BABYLON.AssetsManager}
  86405. */
  86406. AssetsManager.prototype.reset = function () {
  86407. this._isLoading = false;
  86408. this._tasks = new Array();
  86409. return this;
  86410. };
  86411. /**
  86412. * Start the loading process
  86413. * @return the current instance of the {BABYLON.AssetsManager}
  86414. */
  86415. AssetsManager.prototype.load = function () {
  86416. if (this._isLoading) {
  86417. return this;
  86418. }
  86419. this._isLoading = true;
  86420. this._waitingTasksCount = this._tasks.length;
  86421. this._totalTasksCount = this._tasks.length;
  86422. if (this._waitingTasksCount === 0) {
  86423. this._isLoading = false;
  86424. if (this.onFinish) {
  86425. this.onFinish(this._tasks);
  86426. }
  86427. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86428. return this;
  86429. }
  86430. if (this.useDefaultLoadingScreen) {
  86431. this._scene.getEngine().displayLoadingUI();
  86432. }
  86433. for (var index = 0; index < this._tasks.length; index++) {
  86434. var task = this._tasks[index];
  86435. this._runTask(task);
  86436. }
  86437. return this;
  86438. };
  86439. return AssetsManager;
  86440. }());
  86441. BABYLON.AssetsManager = AssetsManager;
  86442. })(BABYLON || (BABYLON = {}));
  86443. //# sourceMappingURL=babylon.assetsManager.js.map
  86444. var BABYLON;
  86445. (function (BABYLON) {
  86446. var serializedGeometries = [];
  86447. var serializeGeometry = function (geometry, serializationGeometries) {
  86448. if (serializedGeometries[geometry.id]) {
  86449. return;
  86450. }
  86451. if (geometry.doNotSerialize) {
  86452. return;
  86453. }
  86454. if (geometry instanceof BABYLON.BoxGeometry) {
  86455. serializationGeometries.boxes.push(geometry.serialize());
  86456. }
  86457. else if (geometry instanceof BABYLON.SphereGeometry) {
  86458. serializationGeometries.spheres.push(geometry.serialize());
  86459. }
  86460. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86461. serializationGeometries.cylinders.push(geometry.serialize());
  86462. }
  86463. else if (geometry instanceof BABYLON.TorusGeometry) {
  86464. serializationGeometries.toruses.push(geometry.serialize());
  86465. }
  86466. else if (geometry instanceof BABYLON.GroundGeometry) {
  86467. serializationGeometries.grounds.push(geometry.serialize());
  86468. }
  86469. else if (geometry instanceof BABYLON.Plane) {
  86470. serializationGeometries.planes.push(geometry.serialize());
  86471. }
  86472. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86473. serializationGeometries.torusKnots.push(geometry.serialize());
  86474. }
  86475. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86476. throw new Error("Unknown primitive type");
  86477. }
  86478. else {
  86479. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86480. }
  86481. serializedGeometries[geometry.id] = true;
  86482. };
  86483. var serializeMesh = function (mesh, serializationScene) {
  86484. var serializationObject = {};
  86485. // Geometry
  86486. var geometry = mesh._geometry;
  86487. if (geometry) {
  86488. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86489. // 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
  86490. serializeGeometry(geometry, serializationScene.geometries);
  86491. }
  86492. }
  86493. // Custom
  86494. if (mesh.serialize) {
  86495. mesh.serialize(serializationObject);
  86496. }
  86497. return serializationObject;
  86498. };
  86499. var finalizeSingleMesh = function (mesh, serializationObject) {
  86500. //only works if the mesh is already loaded
  86501. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86502. //serialize material
  86503. if (mesh.material) {
  86504. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86505. serializationObject.materials = serializationObject.materials || [];
  86506. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86507. serializationObject.materials.push(mesh.material.serialize());
  86508. }
  86509. }
  86510. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86511. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86512. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86513. serializationObject.multiMaterials.push(mesh.material.serialize());
  86514. }
  86515. }
  86516. }
  86517. //serialize geometry
  86518. var geometry = mesh._geometry;
  86519. if (geometry) {
  86520. if (!serializationObject.geometries) {
  86521. serializationObject.geometries = {};
  86522. serializationObject.geometries.boxes = [];
  86523. serializationObject.geometries.spheres = [];
  86524. serializationObject.geometries.cylinders = [];
  86525. serializationObject.geometries.toruses = [];
  86526. serializationObject.geometries.grounds = [];
  86527. serializationObject.geometries.planes = [];
  86528. serializationObject.geometries.torusKnots = [];
  86529. serializationObject.geometries.vertexData = [];
  86530. }
  86531. serializeGeometry(geometry, serializationObject.geometries);
  86532. }
  86533. // Skeletons
  86534. if (mesh.skeleton) {
  86535. serializationObject.skeletons = serializationObject.skeletons || [];
  86536. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86537. }
  86538. //serialize the actual mesh
  86539. serializationObject.meshes = serializationObject.meshes || [];
  86540. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86541. }
  86542. };
  86543. var SceneSerializer = /** @class */ (function () {
  86544. function SceneSerializer() {
  86545. }
  86546. SceneSerializer.ClearCache = function () {
  86547. serializedGeometries = [];
  86548. };
  86549. SceneSerializer.Serialize = function (scene) {
  86550. var serializationObject = {};
  86551. SceneSerializer.ClearCache();
  86552. // Scene
  86553. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86554. serializationObject.autoClear = scene.autoClear;
  86555. serializationObject.clearColor = scene.clearColor.asArray();
  86556. serializationObject.ambientColor = scene.ambientColor.asArray();
  86557. serializationObject.gravity = scene.gravity.asArray();
  86558. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86559. serializationObject.workerCollisions = scene.workerCollisions;
  86560. // Fog
  86561. if (scene.fogMode && scene.fogMode !== 0) {
  86562. serializationObject.fogMode = scene.fogMode;
  86563. serializationObject.fogColor = scene.fogColor.asArray();
  86564. serializationObject.fogStart = scene.fogStart;
  86565. serializationObject.fogEnd = scene.fogEnd;
  86566. serializationObject.fogDensity = scene.fogDensity;
  86567. }
  86568. //Physics
  86569. if (scene.isPhysicsEnabled()) {
  86570. var physicEngine = scene.getPhysicsEngine();
  86571. if (physicEngine) {
  86572. serializationObject.physicsEnabled = true;
  86573. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86574. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86575. }
  86576. }
  86577. // Metadata
  86578. if (scene.metadata) {
  86579. serializationObject.metadata = scene.metadata;
  86580. }
  86581. // Morph targets
  86582. serializationObject.morphTargetManagers = [];
  86583. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86584. var abstractMesh = _a[_i];
  86585. var manager = abstractMesh.morphTargetManager;
  86586. if (manager) {
  86587. serializationObject.morphTargetManagers.push(manager.serialize());
  86588. }
  86589. }
  86590. // Lights
  86591. serializationObject.lights = [];
  86592. var index;
  86593. var light;
  86594. for (index = 0; index < scene.lights.length; index++) {
  86595. light = scene.lights[index];
  86596. if (!light.doNotSerialize) {
  86597. serializationObject.lights.push(light.serialize());
  86598. }
  86599. }
  86600. // Cameras
  86601. serializationObject.cameras = [];
  86602. for (index = 0; index < scene.cameras.length; index++) {
  86603. var camera = scene.cameras[index];
  86604. if (!camera.doNotSerialize) {
  86605. serializationObject.cameras.push(camera.serialize());
  86606. }
  86607. }
  86608. if (scene.activeCamera) {
  86609. serializationObject.activeCameraID = scene.activeCamera.id;
  86610. }
  86611. // Animations
  86612. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86613. // Materials
  86614. serializationObject.materials = [];
  86615. serializationObject.multiMaterials = [];
  86616. var material;
  86617. for (index = 0; index < scene.materials.length; index++) {
  86618. material = scene.materials[index];
  86619. if (!material.doNotSerialize) {
  86620. serializationObject.materials.push(material.serialize());
  86621. }
  86622. }
  86623. // MultiMaterials
  86624. serializationObject.multiMaterials = [];
  86625. for (index = 0; index < scene.multiMaterials.length; index++) {
  86626. var multiMaterial = scene.multiMaterials[index];
  86627. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86628. }
  86629. // Environment texture
  86630. if (scene.environmentTexture) {
  86631. serializationObject.environmentTexture = scene.environmentTexture.name;
  86632. }
  86633. // Skeletons
  86634. serializationObject.skeletons = [];
  86635. for (index = 0; index < scene.skeletons.length; index++) {
  86636. var skeleton = scene.skeletons[index];
  86637. if (!skeleton.doNotSerialize) {
  86638. serializationObject.skeletons.push(skeleton.serialize());
  86639. }
  86640. }
  86641. // Transform nodes
  86642. serializationObject.transformNodes = [];
  86643. for (index = 0; index < scene.transformNodes.length; index++) {
  86644. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86645. }
  86646. // Geometries
  86647. serializationObject.geometries = {};
  86648. serializationObject.geometries.boxes = [];
  86649. serializationObject.geometries.spheres = [];
  86650. serializationObject.geometries.cylinders = [];
  86651. serializationObject.geometries.toruses = [];
  86652. serializationObject.geometries.grounds = [];
  86653. serializationObject.geometries.planes = [];
  86654. serializationObject.geometries.torusKnots = [];
  86655. serializationObject.geometries.vertexData = [];
  86656. serializedGeometries = [];
  86657. var geometries = scene.getGeometries();
  86658. for (index = 0; index < geometries.length; index++) {
  86659. var geometry = geometries[index];
  86660. if (geometry.isReady()) {
  86661. serializeGeometry(geometry, serializationObject.geometries);
  86662. }
  86663. }
  86664. // Meshes
  86665. serializationObject.meshes = [];
  86666. for (index = 0; index < scene.meshes.length; index++) {
  86667. var abstractMesh = scene.meshes[index];
  86668. if (abstractMesh instanceof BABYLON.Mesh) {
  86669. var mesh = abstractMesh;
  86670. if (!mesh.doNotSerialize) {
  86671. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86672. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86673. }
  86674. }
  86675. }
  86676. }
  86677. // Particles Systems
  86678. serializationObject.particleSystems = [];
  86679. for (index = 0; index < scene.particleSystems.length; index++) {
  86680. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86681. }
  86682. // Lens flares
  86683. serializationObject.lensFlareSystems = [];
  86684. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86685. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86686. }
  86687. // Shadows
  86688. serializationObject.shadowGenerators = [];
  86689. for (index = 0; index < scene.lights.length; index++) {
  86690. light = scene.lights[index];
  86691. var shadowGenerator = light.getShadowGenerator();
  86692. if (shadowGenerator) {
  86693. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86694. }
  86695. }
  86696. // Action Manager
  86697. if (scene.actionManager) {
  86698. serializationObject.actions = scene.actionManager.serialize("scene");
  86699. }
  86700. // Audio
  86701. serializationObject.sounds = [];
  86702. for (index = 0; index < scene.soundTracks.length; index++) {
  86703. var soundtrack = scene.soundTracks[index];
  86704. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86705. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86706. }
  86707. }
  86708. return serializationObject;
  86709. };
  86710. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86711. if (withParents === void 0) { withParents = false; }
  86712. if (withChildren === void 0) { withChildren = false; }
  86713. var serializationObject = {};
  86714. SceneSerializer.ClearCache();
  86715. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86716. if (withParents || withChildren) {
  86717. //deliberate for loop! not for each, appended should be processed as well.
  86718. for (var i = 0; i < toSerialize.length; ++i) {
  86719. if (withChildren) {
  86720. toSerialize[i].getDescendants().forEach(function (node) {
  86721. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86722. toSerialize.push(node);
  86723. }
  86724. });
  86725. }
  86726. //make sure the array doesn't contain the object already
  86727. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86728. toSerialize.push(toSerialize[i].parent);
  86729. }
  86730. }
  86731. }
  86732. toSerialize.forEach(function (mesh) {
  86733. finalizeSingleMesh(mesh, serializationObject);
  86734. });
  86735. return serializationObject;
  86736. };
  86737. return SceneSerializer;
  86738. }());
  86739. BABYLON.SceneSerializer = SceneSerializer;
  86740. })(BABYLON || (BABYLON = {}));
  86741. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86742. var BABYLON;
  86743. (function (BABYLON) {
  86744. var ReflectionProbe = /** @class */ (function () {
  86745. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86746. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86747. var _this = this;
  86748. this.name = name;
  86749. this._viewMatrix = BABYLON.Matrix.Identity();
  86750. this._target = BABYLON.Vector3.Zero();
  86751. this._add = BABYLON.Vector3.Zero();
  86752. this._invertYAxis = false;
  86753. this.position = BABYLON.Vector3.Zero();
  86754. this._scene = scene;
  86755. this._scene.reflectionProbes.push(this);
  86756. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86757. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86758. switch (faceIndex) {
  86759. case 0:
  86760. _this._add.copyFromFloats(1, 0, 0);
  86761. break;
  86762. case 1:
  86763. _this._add.copyFromFloats(-1, 0, 0);
  86764. break;
  86765. case 2:
  86766. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86767. break;
  86768. case 3:
  86769. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86770. break;
  86771. case 4:
  86772. _this._add.copyFromFloats(0, 0, 1);
  86773. break;
  86774. case 5:
  86775. _this._add.copyFromFloats(0, 0, -1);
  86776. break;
  86777. }
  86778. if (_this._attachedMesh) {
  86779. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86780. }
  86781. _this.position.addToRef(_this._add, _this._target);
  86782. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86783. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86784. scene._forcedViewPosition = _this.position;
  86785. });
  86786. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86787. scene._forcedViewPosition = null;
  86788. scene.updateTransformMatrix(true);
  86789. });
  86790. if (scene.activeCamera) {
  86791. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86792. }
  86793. }
  86794. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86795. get: function () {
  86796. return this._renderTargetTexture.samples;
  86797. },
  86798. set: function (value) {
  86799. this._renderTargetTexture.samples = value;
  86800. },
  86801. enumerable: true,
  86802. configurable: true
  86803. });
  86804. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86805. get: function () {
  86806. return this._renderTargetTexture.refreshRate;
  86807. },
  86808. set: function (value) {
  86809. this._renderTargetTexture.refreshRate = value;
  86810. },
  86811. enumerable: true,
  86812. configurable: true
  86813. });
  86814. ReflectionProbe.prototype.getScene = function () {
  86815. return this._scene;
  86816. };
  86817. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86818. get: function () {
  86819. return this._renderTargetTexture;
  86820. },
  86821. enumerable: true,
  86822. configurable: true
  86823. });
  86824. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86825. get: function () {
  86826. return this._renderTargetTexture.renderList;
  86827. },
  86828. enumerable: true,
  86829. configurable: true
  86830. });
  86831. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86832. this._attachedMesh = mesh;
  86833. };
  86834. /**
  86835. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86836. *
  86837. * @param renderingGroupId The rendering group id corresponding to its index
  86838. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86839. */
  86840. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86841. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86842. };
  86843. ReflectionProbe.prototype.dispose = function () {
  86844. var index = this._scene.reflectionProbes.indexOf(this);
  86845. if (index !== -1) {
  86846. // Remove from the scene if found
  86847. this._scene.reflectionProbes.splice(index, 1);
  86848. }
  86849. if (this._renderTargetTexture) {
  86850. this._renderTargetTexture.dispose();
  86851. this._renderTargetTexture = null;
  86852. }
  86853. };
  86854. return ReflectionProbe;
  86855. }());
  86856. BABYLON.ReflectionProbe = ReflectionProbe;
  86857. })(BABYLON || (BABYLON = {}));
  86858. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86859. var BABYLON;
  86860. (function (BABYLON) {
  86861. var Layer = /** @class */ (function () {
  86862. function Layer(name, imgUrl, scene, isBackground, color) {
  86863. this.name = name;
  86864. this.scale = new BABYLON.Vector2(1, 1);
  86865. this.offset = new BABYLON.Vector2(0, 0);
  86866. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86867. this.layerMask = 0x0FFFFFFF;
  86868. this._vertexBuffers = {};
  86869. // Events
  86870. /**
  86871. * An event triggered when the layer is disposed.
  86872. * @type {BABYLON.Observable}
  86873. */
  86874. this.onDisposeObservable = new BABYLON.Observable();
  86875. /**
  86876. * An event triggered before rendering the scene
  86877. * @type {BABYLON.Observable}
  86878. */
  86879. this.onBeforeRenderObservable = new BABYLON.Observable();
  86880. /**
  86881. * An event triggered after rendering the scene
  86882. * @type {BABYLON.Observable}
  86883. */
  86884. this.onAfterRenderObservable = new BABYLON.Observable();
  86885. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86886. this.isBackground = isBackground === undefined ? true : isBackground;
  86887. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86888. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86889. this._scene.layers.push(this);
  86890. var engine = this._scene.getEngine();
  86891. // VBO
  86892. var vertices = [];
  86893. vertices.push(1, 1);
  86894. vertices.push(-1, 1);
  86895. vertices.push(-1, -1);
  86896. vertices.push(1, -1);
  86897. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86898. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86899. this._createIndexBuffer();
  86900. // Effects
  86901. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86902. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86903. }
  86904. Object.defineProperty(Layer.prototype, "onDispose", {
  86905. set: function (callback) {
  86906. if (this._onDisposeObserver) {
  86907. this.onDisposeObservable.remove(this._onDisposeObserver);
  86908. }
  86909. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86910. },
  86911. enumerable: true,
  86912. configurable: true
  86913. });
  86914. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86915. set: function (callback) {
  86916. if (this._onBeforeRenderObserver) {
  86917. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86918. }
  86919. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86920. },
  86921. enumerable: true,
  86922. configurable: true
  86923. });
  86924. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86925. set: function (callback) {
  86926. if (this._onAfterRenderObserver) {
  86927. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86928. }
  86929. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86930. },
  86931. enumerable: true,
  86932. configurable: true
  86933. });
  86934. Layer.prototype._createIndexBuffer = function () {
  86935. var engine = this._scene.getEngine();
  86936. // Indices
  86937. var indices = [];
  86938. indices.push(0);
  86939. indices.push(1);
  86940. indices.push(2);
  86941. indices.push(0);
  86942. indices.push(2);
  86943. indices.push(3);
  86944. this._indexBuffer = engine.createIndexBuffer(indices);
  86945. };
  86946. Layer.prototype._rebuild = function () {
  86947. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86948. if (vb) {
  86949. vb._rebuild();
  86950. }
  86951. this._createIndexBuffer();
  86952. };
  86953. Layer.prototype.render = function () {
  86954. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86955. // Check
  86956. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86957. return;
  86958. var engine = this._scene.getEngine();
  86959. this.onBeforeRenderObservable.notifyObservers(this);
  86960. // Render
  86961. engine.enableEffect(currentEffect);
  86962. engine.setState(false);
  86963. // Texture
  86964. currentEffect.setTexture("textureSampler", this.texture);
  86965. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86966. // Color
  86967. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86968. // Scale / offset
  86969. currentEffect.setVector2("offset", this.offset);
  86970. currentEffect.setVector2("scale", this.scale);
  86971. // VBOs
  86972. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86973. // Draw order
  86974. if (!this.alphaTest) {
  86975. engine.setAlphaMode(this.alphaBlendingMode);
  86976. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86977. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86978. }
  86979. else {
  86980. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86981. }
  86982. this.onAfterRenderObservable.notifyObservers(this);
  86983. };
  86984. Layer.prototype.dispose = function () {
  86985. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86986. if (vertexBuffer) {
  86987. vertexBuffer.dispose();
  86988. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86989. }
  86990. if (this._indexBuffer) {
  86991. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86992. this._indexBuffer = null;
  86993. }
  86994. if (this.texture) {
  86995. this.texture.dispose();
  86996. this.texture = null;
  86997. }
  86998. // Remove from scene
  86999. var index = this._scene.layers.indexOf(this);
  87000. this._scene.layers.splice(index, 1);
  87001. // Callback
  87002. this.onDisposeObservable.notifyObservers(this);
  87003. this.onDisposeObservable.clear();
  87004. this.onAfterRenderObservable.clear();
  87005. this.onBeforeRenderObservable.clear();
  87006. };
  87007. return Layer;
  87008. }());
  87009. BABYLON.Layer = Layer;
  87010. })(BABYLON || (BABYLON = {}));
  87011. //# sourceMappingURL=babylon.layer.js.map
  87012. var BABYLON;
  87013. (function (BABYLON) {
  87014. var TextureTools = /** @class */ (function () {
  87015. function TextureTools() {
  87016. }
  87017. /**
  87018. * Uses the GPU to create a copy texture rescaled at a given size
  87019. * @param texture Texture to copy from
  87020. * @param width Desired width
  87021. * @param height Desired height
  87022. * @return Generated texture
  87023. */
  87024. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87025. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87026. var scene = texture.getScene();
  87027. var engine = scene.getEngine();
  87028. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87029. rtt.wrapU = texture.wrapU;
  87030. rtt.wrapV = texture.wrapV;
  87031. rtt.uOffset = texture.uOffset;
  87032. rtt.vOffset = texture.vOffset;
  87033. rtt.uScale = texture.uScale;
  87034. rtt.vScale = texture.vScale;
  87035. rtt.uAng = texture.uAng;
  87036. rtt.vAng = texture.vAng;
  87037. rtt.wAng = texture.wAng;
  87038. rtt.coordinatesIndex = texture.coordinatesIndex;
  87039. rtt.level = texture.level;
  87040. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87041. rtt._texture.isReady = false;
  87042. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87043. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87044. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87045. passPostProcess.getEffect().executeWhenCompiled(function () {
  87046. passPostProcess.onApply = function (effect) {
  87047. effect.setTexture("textureSampler", texture);
  87048. };
  87049. var internalTexture = rtt.getInternalTexture();
  87050. if (internalTexture) {
  87051. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87052. engine.unBindFramebuffer(internalTexture);
  87053. rtt.disposeFramebufferObjects();
  87054. passPostProcess.dispose();
  87055. internalTexture.isReady = true;
  87056. }
  87057. });
  87058. return rtt;
  87059. };
  87060. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87061. if (!scene._environmentBRDFTexture) {
  87062. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87063. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87064. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87065. scene._environmentBRDFTexture = texture;
  87066. }
  87067. return scene._environmentBRDFTexture;
  87068. };
  87069. 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=";
  87070. return TextureTools;
  87071. }());
  87072. BABYLON.TextureTools = TextureTools;
  87073. })(BABYLON || (BABYLON = {}));
  87074. //# sourceMappingURL=babylon.textureTools.js.map
  87075. var BABYLON;
  87076. (function (BABYLON) {
  87077. var FramingBehavior = /** @class */ (function () {
  87078. function FramingBehavior() {
  87079. this._mode = FramingBehavior.FitFrustumSidesMode;
  87080. this._radiusScale = 1.0;
  87081. this._positionScale = 0.5;
  87082. this._defaultElevation = 0.3;
  87083. this._elevationReturnTime = 1500;
  87084. this._elevationReturnWaitTime = 1000;
  87085. this._zoomStopsAnimation = false;
  87086. this._framingTime = 1500;
  87087. this._isPointerDown = false;
  87088. this._lastInteractionTime = -Infinity;
  87089. // Framing control
  87090. this._animatables = new Array();
  87091. this._betaIsAnimating = false;
  87092. }
  87093. Object.defineProperty(FramingBehavior.prototype, "name", {
  87094. get: function () {
  87095. return "Framing";
  87096. },
  87097. enumerable: true,
  87098. configurable: true
  87099. });
  87100. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87101. /**
  87102. * Gets current mode used by the behavior.
  87103. */
  87104. get: function () {
  87105. return this._mode;
  87106. },
  87107. /**
  87108. * Sets the current mode used by the behavior
  87109. */
  87110. set: function (mode) {
  87111. this._mode = mode;
  87112. },
  87113. enumerable: true,
  87114. configurable: true
  87115. });
  87116. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87117. /**
  87118. * Gets the scale applied to the radius
  87119. */
  87120. get: function () {
  87121. return this._radiusScale;
  87122. },
  87123. /**
  87124. * Sets the scale applied to the radius (1 by default)
  87125. */
  87126. set: function (radius) {
  87127. this._radiusScale = radius;
  87128. },
  87129. enumerable: true,
  87130. configurable: true
  87131. });
  87132. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87133. /**
  87134. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87135. */
  87136. get: function () {
  87137. return this._positionScale;
  87138. },
  87139. /**
  87140. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87141. */
  87142. set: function (scale) {
  87143. this._positionScale = scale;
  87144. },
  87145. enumerable: true,
  87146. configurable: true
  87147. });
  87148. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87149. /**
  87150. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87151. * behaviour is triggered, in radians.
  87152. */
  87153. get: function () {
  87154. return this._defaultElevation;
  87155. },
  87156. /**
  87157. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87158. * behaviour is triggered, in radians.
  87159. */
  87160. set: function (elevation) {
  87161. this._defaultElevation = elevation;
  87162. },
  87163. enumerable: true,
  87164. configurable: true
  87165. });
  87166. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87167. /**
  87168. * Gets the time (in milliseconds) taken to return to the default beta position.
  87169. * Negative value indicates camera should not return to default.
  87170. */
  87171. get: function () {
  87172. return this._elevationReturnTime;
  87173. },
  87174. /**
  87175. * Sets the time (in milliseconds) taken to return to the default beta position.
  87176. * Negative value indicates camera should not return to default.
  87177. */
  87178. set: function (speed) {
  87179. this._elevationReturnTime = speed;
  87180. },
  87181. enumerable: true,
  87182. configurable: true
  87183. });
  87184. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87185. /**
  87186. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87187. */
  87188. get: function () {
  87189. return this._elevationReturnWaitTime;
  87190. },
  87191. /**
  87192. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87193. */
  87194. set: function (time) {
  87195. this._elevationReturnWaitTime = time;
  87196. },
  87197. enumerable: true,
  87198. configurable: true
  87199. });
  87200. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87201. /**
  87202. * Gets the flag that indicates if user zooming should stop animation.
  87203. */
  87204. get: function () {
  87205. return this._zoomStopsAnimation;
  87206. },
  87207. /**
  87208. * Sets the flag that indicates if user zooming should stop animation.
  87209. */
  87210. set: function (flag) {
  87211. this._zoomStopsAnimation = flag;
  87212. },
  87213. enumerable: true,
  87214. configurable: true
  87215. });
  87216. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87217. /**
  87218. * Gets the transition time when framing the mesh, in milliseconds
  87219. */
  87220. get: function () {
  87221. return this._framingTime;
  87222. },
  87223. /**
  87224. * Sets the transition time when framing the mesh, in milliseconds
  87225. */
  87226. set: function (time) {
  87227. this._framingTime = time;
  87228. },
  87229. enumerable: true,
  87230. configurable: true
  87231. });
  87232. FramingBehavior.prototype.init = function () {
  87233. // Do notihng
  87234. };
  87235. FramingBehavior.prototype.attach = function (camera) {
  87236. var _this = this;
  87237. this._attachedCamera = camera;
  87238. var scene = this._attachedCamera.getScene();
  87239. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87240. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87241. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87242. _this._isPointerDown = true;
  87243. return;
  87244. }
  87245. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87246. _this._isPointerDown = false;
  87247. }
  87248. });
  87249. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87250. if (mesh) {
  87251. _this.zoomOnMesh(mesh);
  87252. }
  87253. });
  87254. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87255. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87256. _this._applyUserInteraction();
  87257. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87258. // back to the default position after a given timeout
  87259. _this._maintainCameraAboveGround();
  87260. });
  87261. };
  87262. FramingBehavior.prototype.detach = function () {
  87263. if (!this._attachedCamera) {
  87264. return;
  87265. }
  87266. var scene = this._attachedCamera.getScene();
  87267. if (this._onPrePointerObservableObserver) {
  87268. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87269. }
  87270. if (this._onAfterCheckInputsObserver) {
  87271. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87272. }
  87273. if (this._onMeshTargetChangedObserver) {
  87274. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87275. }
  87276. this._attachedCamera = null;
  87277. };
  87278. /**
  87279. * Targets the given mesh and updates zoom level accordingly.
  87280. * @param mesh The mesh to target.
  87281. * @param radius Optional. If a cached radius position already exists, overrides default.
  87282. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87283. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87284. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87285. */
  87286. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87287. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87288. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87289. mesh.computeWorldMatrix(true);
  87290. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87291. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87292. };
  87293. /**
  87294. * Targets the given mesh with its children and updates zoom level accordingly.
  87295. * @param mesh The mesh to target.
  87296. * @param radius Optional. If a cached radius position already exists, overrides default.
  87297. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87298. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87299. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87300. */
  87301. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87302. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87303. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87304. mesh.computeWorldMatrix(true);
  87305. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87306. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87307. };
  87308. /**
  87309. * Targets the given meshes with their children and updates zoom level accordingly.
  87310. * @param meshes The mesh to target.
  87311. * @param radius Optional. If a cached radius position already exists, overrides default.
  87312. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87313. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87314. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87315. */
  87316. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87317. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87318. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87319. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87320. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87321. for (var i = 0; i < meshes.length; i++) {
  87322. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87323. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87324. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87325. }
  87326. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87327. };
  87328. /**
  87329. * Targets the given mesh and updates zoom level accordingly.
  87330. * @param mesh The mesh to target.
  87331. * @param radius Optional. If a cached radius position already exists, overrides default.
  87332. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87333. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87334. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87335. */
  87336. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87337. var _this = this;
  87338. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87339. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87340. var zoomTarget;
  87341. if (!this._attachedCamera) {
  87342. return;
  87343. }
  87344. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87345. var bottom = minimumWorld.y;
  87346. var top = maximumWorld.y;
  87347. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87348. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87349. if (focusOnOriginXZ) {
  87350. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87351. }
  87352. else {
  87353. var centerWorld = minimumWorld.add(radiusWorld);
  87354. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87355. }
  87356. if (!this._vectorTransition) {
  87357. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87358. }
  87359. this._betaIsAnimating = true;
  87360. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87361. if (animatable) {
  87362. this._animatables.push(animatable);
  87363. }
  87364. // sets the radius and lower radius bounds
  87365. // Small delta ensures camera is not always at lower zoom limit.
  87366. var radius = 0;
  87367. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87368. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87369. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87370. radius = position;
  87371. }
  87372. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87373. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87374. if (this._attachedCamera.lowerRadiusLimit === null) {
  87375. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87376. }
  87377. }
  87378. // Set sensibilities
  87379. var extend = maximumWorld.subtract(minimumWorld).length();
  87380. this._attachedCamera.panningSensibility = 5000 / extend;
  87381. this._attachedCamera.wheelPrecision = 100 / radius;
  87382. // transition to new radius
  87383. if (!this._radiusTransition) {
  87384. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87385. }
  87386. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87387. _this.stopAllAnimations();
  87388. if (onAnimationEnd) {
  87389. onAnimationEnd();
  87390. }
  87391. if (_this._attachedCamera) {
  87392. _this._attachedCamera.storeState();
  87393. }
  87394. });
  87395. if (animatable) {
  87396. this._animatables.push(animatable);
  87397. }
  87398. };
  87399. /**
  87400. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87401. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87402. * frustum width.
  87403. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87404. * to fully enclose the mesh in the viewing frustum.
  87405. */
  87406. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87407. var size = maximumWorld.subtract(minimumWorld);
  87408. var boxVectorGlobalDiagonal = size.length();
  87409. var frustumSlope = this._getFrustumSlope();
  87410. // Formula for setting distance
  87411. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87412. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87413. // Horizon distance
  87414. var radius = radiusWithoutFraming * this._radiusScale;
  87415. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87416. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87417. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87418. var camera = this._attachedCamera;
  87419. if (!camera) {
  87420. return 0;
  87421. }
  87422. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87423. // Don't exceed the requested limit
  87424. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87425. }
  87426. // Don't exceed the upper radius limit
  87427. if (camera.upperRadiusLimit) {
  87428. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87429. }
  87430. return distance;
  87431. };
  87432. /**
  87433. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87434. * is automatically returned to its default position (expected to be above ground plane).
  87435. */
  87436. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87437. var _this = this;
  87438. if (this._elevationReturnTime < 0) {
  87439. return;
  87440. }
  87441. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87442. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87443. var limitBeta = Math.PI * 0.5;
  87444. // Bring the camera back up if below the ground plane
  87445. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87446. this._betaIsAnimating = true;
  87447. //Transition to new position
  87448. this.stopAllAnimations();
  87449. if (!this._betaTransition) {
  87450. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87451. }
  87452. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87453. _this._clearAnimationLocks();
  87454. _this.stopAllAnimations();
  87455. });
  87456. if (animatabe) {
  87457. this._animatables.push(animatabe);
  87458. }
  87459. }
  87460. };
  87461. /**
  87462. * Returns the frustum slope based on the canvas ratio and camera FOV
  87463. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87464. */
  87465. FramingBehavior.prototype._getFrustumSlope = function () {
  87466. // Calculate the viewport ratio
  87467. // Aspect Ratio is Height/Width.
  87468. var camera = this._attachedCamera;
  87469. if (!camera) {
  87470. return BABYLON.Vector2.Zero();
  87471. }
  87472. var engine = camera.getScene().getEngine();
  87473. var aspectRatio = engine.getAspectRatio(camera);
  87474. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87475. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87476. var frustumSlopeY = Math.tan(camera.fov / 2);
  87477. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87478. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87479. // along the forward vector.
  87480. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87481. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87482. };
  87483. /**
  87484. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87485. */
  87486. FramingBehavior.prototype._clearAnimationLocks = function () {
  87487. this._betaIsAnimating = false;
  87488. };
  87489. /**
  87490. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87491. */
  87492. FramingBehavior.prototype._applyUserInteraction = function () {
  87493. if (this.isUserIsMoving) {
  87494. this._lastInteractionTime = BABYLON.Tools.Now;
  87495. this.stopAllAnimations();
  87496. this._clearAnimationLocks();
  87497. }
  87498. };
  87499. /**
  87500. * Stops and removes all animations that have been applied to the camera
  87501. */
  87502. FramingBehavior.prototype.stopAllAnimations = function () {
  87503. if (this._attachedCamera) {
  87504. this._attachedCamera.animations = [];
  87505. }
  87506. while (this._animatables.length) {
  87507. if (this._animatables[0]) {
  87508. this._animatables[0].onAnimationEnd = null;
  87509. this._animatables[0].stop();
  87510. }
  87511. this._animatables.shift();
  87512. }
  87513. };
  87514. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87515. /**
  87516. * Gets a value indicating if the user is moving the camera
  87517. */
  87518. get: function () {
  87519. if (!this._attachedCamera) {
  87520. return false;
  87521. }
  87522. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87523. this._attachedCamera.inertialBetaOffset !== 0 ||
  87524. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87525. this._attachedCamera.inertialPanningX !== 0 ||
  87526. this._attachedCamera.inertialPanningY !== 0 ||
  87527. this._isPointerDown;
  87528. },
  87529. enumerable: true,
  87530. configurable: true
  87531. });
  87532. /**
  87533. * The easing function used by animations
  87534. */
  87535. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87536. /**
  87537. * The easing mode used by animations
  87538. */
  87539. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87540. // Statics
  87541. /**
  87542. * The camera can move all the way towards the mesh.
  87543. */
  87544. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87545. /**
  87546. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87547. */
  87548. FramingBehavior.FitFrustumSidesMode = 1;
  87549. return FramingBehavior;
  87550. }());
  87551. BABYLON.FramingBehavior = FramingBehavior;
  87552. })(BABYLON || (BABYLON = {}));
  87553. //# sourceMappingURL=babylon.framingBehavior.js.map
  87554. var BABYLON;
  87555. (function (BABYLON) {
  87556. /**
  87557. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87558. */
  87559. var BouncingBehavior = /** @class */ (function () {
  87560. function BouncingBehavior() {
  87561. /**
  87562. * The duration of the animation, in milliseconds
  87563. */
  87564. this.transitionDuration = 450;
  87565. /**
  87566. * Length of the distance animated by the transition when lower radius is reached
  87567. */
  87568. this.lowerRadiusTransitionRange = 2;
  87569. /**
  87570. * Length of the distance animated by the transition when upper radius is reached
  87571. */
  87572. this.upperRadiusTransitionRange = -2;
  87573. this._autoTransitionRange = false;
  87574. // Animations
  87575. this._radiusIsAnimating = false;
  87576. this._radiusBounceTransition = null;
  87577. this._animatables = new Array();
  87578. }
  87579. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87580. get: function () {
  87581. return "Bouncing";
  87582. },
  87583. enumerable: true,
  87584. configurable: true
  87585. });
  87586. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87587. /**
  87588. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87589. */
  87590. get: function () {
  87591. return this._autoTransitionRange;
  87592. },
  87593. /**
  87594. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87595. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87596. */
  87597. set: function (value) {
  87598. var _this = this;
  87599. if (this._autoTransitionRange === value) {
  87600. return;
  87601. }
  87602. this._autoTransitionRange = value;
  87603. var camera = this._attachedCamera;
  87604. if (!camera) {
  87605. return;
  87606. }
  87607. if (value) {
  87608. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87609. if (!mesh) {
  87610. return;
  87611. }
  87612. mesh.computeWorldMatrix(true);
  87613. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87614. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87615. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87616. });
  87617. }
  87618. else if (this._onMeshTargetChangedObserver) {
  87619. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87620. }
  87621. },
  87622. enumerable: true,
  87623. configurable: true
  87624. });
  87625. BouncingBehavior.prototype.init = function () {
  87626. // Do notihng
  87627. };
  87628. BouncingBehavior.prototype.attach = function (camera) {
  87629. var _this = this;
  87630. this._attachedCamera = camera;
  87631. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87632. if (!_this._attachedCamera) {
  87633. return;
  87634. }
  87635. // Add the bounce animation to the lower radius limit
  87636. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87637. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87638. }
  87639. // Add the bounce animation to the upper radius limit
  87640. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87641. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87642. }
  87643. });
  87644. };
  87645. BouncingBehavior.prototype.detach = function () {
  87646. if (!this._attachedCamera) {
  87647. return;
  87648. }
  87649. if (this._onAfterCheckInputsObserver) {
  87650. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87651. }
  87652. if (this._onMeshTargetChangedObserver) {
  87653. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87654. }
  87655. this._attachedCamera = null;
  87656. };
  87657. /**
  87658. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87659. * @param radiusLimit The limit to check against.
  87660. * @return Bool to indicate if at limit.
  87661. */
  87662. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87663. if (!this._attachedCamera) {
  87664. return false;
  87665. }
  87666. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87667. return true;
  87668. }
  87669. return false;
  87670. };
  87671. /**
  87672. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87673. * @param radiusDelta The delta by which to animate to. Can be negative.
  87674. */
  87675. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87676. var _this = this;
  87677. if (!this._attachedCamera) {
  87678. return;
  87679. }
  87680. if (!this._radiusBounceTransition) {
  87681. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87682. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87683. }
  87684. // Prevent zoom until bounce has completed
  87685. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87686. this._attachedCamera.wheelPrecision = Infinity;
  87687. this._attachedCamera.inertialRadiusOffset = 0;
  87688. // Animate to the radius limit
  87689. this.stopAllAnimations();
  87690. this._radiusIsAnimating = true;
  87691. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87692. if (animatable) {
  87693. this._animatables.push(animatable);
  87694. }
  87695. };
  87696. /**
  87697. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87698. */
  87699. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87700. this._radiusIsAnimating = false;
  87701. if (this._attachedCamera) {
  87702. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87703. }
  87704. };
  87705. /**
  87706. * Stops and removes all animations that have been applied to the camera
  87707. */
  87708. BouncingBehavior.prototype.stopAllAnimations = function () {
  87709. if (this._attachedCamera) {
  87710. this._attachedCamera.animations = [];
  87711. }
  87712. while (this._animatables.length) {
  87713. this._animatables[0].onAnimationEnd = null;
  87714. this._animatables[0].stop();
  87715. this._animatables.shift();
  87716. }
  87717. };
  87718. /**
  87719. * The easing function used by animations
  87720. */
  87721. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87722. /**
  87723. * The easing mode used by animations
  87724. */
  87725. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87726. return BouncingBehavior;
  87727. }());
  87728. BABYLON.BouncingBehavior = BouncingBehavior;
  87729. })(BABYLON || (BABYLON = {}));
  87730. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87731. var BABYLON;
  87732. (function (BABYLON) {
  87733. var AutoRotationBehavior = /** @class */ (function () {
  87734. function AutoRotationBehavior() {
  87735. this._zoomStopsAnimation = false;
  87736. this._idleRotationSpeed = 0.05;
  87737. this._idleRotationWaitTime = 2000;
  87738. this._idleRotationSpinupTime = 2000;
  87739. this._isPointerDown = false;
  87740. this._lastFrameTime = null;
  87741. this._lastInteractionTime = -Infinity;
  87742. this._cameraRotationSpeed = 0;
  87743. this._lastFrameRadius = 0;
  87744. }
  87745. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87746. get: function () {
  87747. return "AutoRotation";
  87748. },
  87749. enumerable: true,
  87750. configurable: true
  87751. });
  87752. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87753. /**
  87754. * Gets the flag that indicates if user zooming should stop animation.
  87755. */
  87756. get: function () {
  87757. return this._zoomStopsAnimation;
  87758. },
  87759. /**
  87760. * Sets the flag that indicates if user zooming should stop animation.
  87761. */
  87762. set: function (flag) {
  87763. this._zoomStopsAnimation = flag;
  87764. },
  87765. enumerable: true,
  87766. configurable: true
  87767. });
  87768. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87769. /**
  87770. * Gets the default speed at which the camera rotates around the model.
  87771. */
  87772. get: function () {
  87773. return this._idleRotationSpeed;
  87774. },
  87775. /**
  87776. * Sets the default speed at which the camera rotates around the model.
  87777. */
  87778. set: function (speed) {
  87779. this._idleRotationSpeed = speed;
  87780. },
  87781. enumerable: true,
  87782. configurable: true
  87783. });
  87784. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87785. /**
  87786. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87787. */
  87788. get: function () {
  87789. return this._idleRotationWaitTime;
  87790. },
  87791. /**
  87792. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87793. */
  87794. set: function (time) {
  87795. this._idleRotationWaitTime = time;
  87796. },
  87797. enumerable: true,
  87798. configurable: true
  87799. });
  87800. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87801. /**
  87802. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87803. */
  87804. get: function () {
  87805. return this._idleRotationSpinupTime;
  87806. },
  87807. /**
  87808. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87809. */
  87810. set: function (time) {
  87811. this._idleRotationSpinupTime = time;
  87812. },
  87813. enumerable: true,
  87814. configurable: true
  87815. });
  87816. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87817. /**
  87818. * Gets a value indicating if the camera is currently rotating because of this behavior
  87819. */
  87820. get: function () {
  87821. return Math.abs(this._cameraRotationSpeed) > 0;
  87822. },
  87823. enumerable: true,
  87824. configurable: true
  87825. });
  87826. AutoRotationBehavior.prototype.init = function () {
  87827. // Do notihng
  87828. };
  87829. AutoRotationBehavior.prototype.attach = function (camera) {
  87830. var _this = this;
  87831. this._attachedCamera = camera;
  87832. var scene = this._attachedCamera.getScene();
  87833. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87834. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87835. _this._isPointerDown = true;
  87836. return;
  87837. }
  87838. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87839. _this._isPointerDown = false;
  87840. }
  87841. });
  87842. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87843. var now = BABYLON.Tools.Now;
  87844. var dt = 0;
  87845. if (_this._lastFrameTime != null) {
  87846. dt = now - _this._lastFrameTime;
  87847. }
  87848. _this._lastFrameTime = now;
  87849. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87850. _this._applyUserInteraction();
  87851. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87852. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87853. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87854. // Step camera rotation by rotation speed
  87855. if (_this._attachedCamera) {
  87856. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87857. }
  87858. });
  87859. };
  87860. AutoRotationBehavior.prototype.detach = function () {
  87861. if (!this._attachedCamera) {
  87862. return;
  87863. }
  87864. var scene = this._attachedCamera.getScene();
  87865. if (this._onPrePointerObservableObserver) {
  87866. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87867. }
  87868. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87869. this._attachedCamera = null;
  87870. };
  87871. /**
  87872. * Returns true if user is scrolling.
  87873. * @return true if user is scrolling.
  87874. */
  87875. AutoRotationBehavior.prototype._userIsZooming = function () {
  87876. if (!this._attachedCamera) {
  87877. return false;
  87878. }
  87879. return this._attachedCamera.inertialRadiusOffset !== 0;
  87880. };
  87881. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87882. if (!this._attachedCamera) {
  87883. return false;
  87884. }
  87885. var zoomHasHitLimit = false;
  87886. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87887. zoomHasHitLimit = true;
  87888. }
  87889. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87890. this._lastFrameRadius = this._attachedCamera.radius;
  87891. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87892. };
  87893. /**
  87894. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87895. */
  87896. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87897. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87898. this._lastInteractionTime = BABYLON.Tools.Now;
  87899. }
  87900. };
  87901. // Tools
  87902. AutoRotationBehavior.prototype._userIsMoving = function () {
  87903. if (!this._attachedCamera) {
  87904. return false;
  87905. }
  87906. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87907. this._attachedCamera.inertialBetaOffset !== 0 ||
  87908. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87909. this._attachedCamera.inertialPanningX !== 0 ||
  87910. this._attachedCamera.inertialPanningY !== 0 ||
  87911. this._isPointerDown;
  87912. };
  87913. return AutoRotationBehavior;
  87914. }());
  87915. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87916. })(BABYLON || (BABYLON = {}));
  87917. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87918. var BABYLON;
  87919. (function (BABYLON) {
  87920. /**
  87921. * This class can be used to get instrumentation data from a Babylon engine
  87922. */
  87923. var EngineInstrumentation = /** @class */ (function () {
  87924. function EngineInstrumentation(engine) {
  87925. this.engine = engine;
  87926. this._captureGPUFrameTime = false;
  87927. this._gpuFrameTime = new BABYLON.PerfCounter();
  87928. this._captureShaderCompilationTime = false;
  87929. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87930. // Observers
  87931. this._onBeginFrameObserver = null;
  87932. this._onEndFrameObserver = null;
  87933. this._onBeforeShaderCompilationObserver = null;
  87934. this._onAfterShaderCompilationObserver = null;
  87935. }
  87936. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87937. // Properties
  87938. /**
  87939. * Gets the perf counter used for GPU frame time
  87940. */
  87941. get: function () {
  87942. return this._gpuFrameTime;
  87943. },
  87944. enumerable: true,
  87945. configurable: true
  87946. });
  87947. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87948. /**
  87949. * Gets the GPU frame time capture status
  87950. */
  87951. get: function () {
  87952. return this._captureGPUFrameTime;
  87953. },
  87954. /**
  87955. * Enable or disable the GPU frame time capture
  87956. */
  87957. set: function (value) {
  87958. var _this = this;
  87959. if (value === this._captureGPUFrameTime) {
  87960. return;
  87961. }
  87962. this._captureGPUFrameTime = value;
  87963. if (value) {
  87964. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87965. if (!_this._gpuFrameTimeToken) {
  87966. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87967. }
  87968. });
  87969. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87970. if (!_this._gpuFrameTimeToken) {
  87971. return;
  87972. }
  87973. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87974. if (time > -1) {
  87975. _this._gpuFrameTimeToken = null;
  87976. _this._gpuFrameTime.fetchNewFrame();
  87977. _this._gpuFrameTime.addCount(time, true);
  87978. }
  87979. });
  87980. }
  87981. else {
  87982. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87983. this._onBeginFrameObserver = null;
  87984. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87985. this._onEndFrameObserver = null;
  87986. }
  87987. },
  87988. enumerable: true,
  87989. configurable: true
  87990. });
  87991. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87992. /**
  87993. * Gets the perf counter used for shader compilation time
  87994. */
  87995. get: function () {
  87996. return this._shaderCompilationTime;
  87997. },
  87998. enumerable: true,
  87999. configurable: true
  88000. });
  88001. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88002. /**
  88003. * Gets the shader compilation time capture status
  88004. */
  88005. get: function () {
  88006. return this._captureShaderCompilationTime;
  88007. },
  88008. /**
  88009. * Enable or disable the shader compilation time capture
  88010. */
  88011. set: function (value) {
  88012. var _this = this;
  88013. if (value === this._captureShaderCompilationTime) {
  88014. return;
  88015. }
  88016. this._captureShaderCompilationTime = value;
  88017. if (value) {
  88018. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88019. _this._shaderCompilationTime.fetchNewFrame();
  88020. _this._shaderCompilationTime.beginMonitoring();
  88021. });
  88022. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88023. _this._shaderCompilationTime.endMonitoring();
  88024. });
  88025. }
  88026. else {
  88027. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88028. this._onBeforeShaderCompilationObserver = null;
  88029. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88030. this._onAfterShaderCompilationObserver = null;
  88031. }
  88032. },
  88033. enumerable: true,
  88034. configurable: true
  88035. });
  88036. EngineInstrumentation.prototype.dispose = function () {
  88037. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88038. this._onBeginFrameObserver = null;
  88039. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88040. this._onEndFrameObserver = null;
  88041. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88042. this._onBeforeShaderCompilationObserver = null;
  88043. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88044. this._onAfterShaderCompilationObserver = null;
  88045. this.engine = null;
  88046. };
  88047. return EngineInstrumentation;
  88048. }());
  88049. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88050. })(BABYLON || (BABYLON = {}));
  88051. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88052. var BABYLON;
  88053. (function (BABYLON) {
  88054. /**
  88055. * This class can be used to get instrumentation data from a Babylon engine
  88056. */
  88057. var SceneInstrumentation = /** @class */ (function () {
  88058. function SceneInstrumentation(scene) {
  88059. var _this = this;
  88060. this.scene = scene;
  88061. this._captureActiveMeshesEvaluationTime = false;
  88062. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88063. this._captureRenderTargetsRenderTime = false;
  88064. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88065. this._captureFrameTime = false;
  88066. this._frameTime = new BABYLON.PerfCounter();
  88067. this._captureRenderTime = false;
  88068. this._renderTime = new BABYLON.PerfCounter();
  88069. this._captureInterFrameTime = false;
  88070. this._interFrameTime = new BABYLON.PerfCounter();
  88071. this._captureParticlesRenderTime = false;
  88072. this._particlesRenderTime = new BABYLON.PerfCounter();
  88073. this._captureSpritesRenderTime = false;
  88074. this._spritesRenderTime = new BABYLON.PerfCounter();
  88075. this._capturePhysicsTime = false;
  88076. this._physicsTime = new BABYLON.PerfCounter();
  88077. this._captureAnimationsTime = false;
  88078. this._animationsTime = new BABYLON.PerfCounter();
  88079. // Observers
  88080. this._onBeforeActiveMeshesEvaluationObserver = null;
  88081. this._onAfterActiveMeshesEvaluationObserver = null;
  88082. this._onBeforeRenderTargetsRenderObserver = null;
  88083. this._onAfterRenderTargetsRenderObserver = null;
  88084. this._onAfterRenderObserver = null;
  88085. this._onBeforeDrawPhaseObserver = null;
  88086. this._onAfterDrawPhaseObserver = null;
  88087. this._onBeforeAnimationsObserver = null;
  88088. this._onBeforeParticlesRenderingObserver = null;
  88089. this._onAfterParticlesRenderingObserver = null;
  88090. this._onBeforeSpritesRenderingObserver = null;
  88091. this._onAfterSpritesRenderingObserver = null;
  88092. this._onBeforePhysicsObserver = null;
  88093. this._onAfterPhysicsObserver = null;
  88094. this._onAfterAnimationsObserver = null;
  88095. // Before render
  88096. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88097. if (_this._captureActiveMeshesEvaluationTime) {
  88098. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88099. }
  88100. if (_this._captureRenderTargetsRenderTime) {
  88101. _this._renderTargetsRenderTime.fetchNewFrame();
  88102. }
  88103. if (_this._captureFrameTime) {
  88104. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88105. _this._frameTime.beginMonitoring();
  88106. }
  88107. if (_this._captureInterFrameTime) {
  88108. _this._interFrameTime.endMonitoring();
  88109. }
  88110. if (_this._captureParticlesRenderTime) {
  88111. _this._particlesRenderTime.fetchNewFrame();
  88112. }
  88113. if (_this._captureSpritesRenderTime) {
  88114. _this._spritesRenderTime.fetchNewFrame();
  88115. }
  88116. if (_this._captureAnimationsTime) {
  88117. _this._animationsTime.beginMonitoring();
  88118. }
  88119. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88120. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88121. });
  88122. // After render
  88123. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88124. if (_this._captureFrameTime) {
  88125. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88126. _this._frameTime.endMonitoring();
  88127. }
  88128. if (_this._captureRenderTime) {
  88129. _this._renderTime.endMonitoring(false);
  88130. }
  88131. if (_this._captureInterFrameTime) {
  88132. _this._interFrameTime.beginMonitoring();
  88133. }
  88134. });
  88135. }
  88136. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88137. // Properties
  88138. /**
  88139. * Gets the perf counter used for active meshes evaluation time
  88140. */
  88141. get: function () {
  88142. return this._activeMeshesEvaluationTime;
  88143. },
  88144. enumerable: true,
  88145. configurable: true
  88146. });
  88147. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88148. /**
  88149. * Gets the active meshes evaluation time capture status
  88150. */
  88151. get: function () {
  88152. return this._captureActiveMeshesEvaluationTime;
  88153. },
  88154. /**
  88155. * Enable or disable the active meshes evaluation time capture
  88156. */
  88157. set: function (value) {
  88158. var _this = this;
  88159. if (value === this._captureActiveMeshesEvaluationTime) {
  88160. return;
  88161. }
  88162. this._captureActiveMeshesEvaluationTime = value;
  88163. if (value) {
  88164. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88165. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88166. _this._activeMeshesEvaluationTime.beginMonitoring();
  88167. });
  88168. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88169. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88170. _this._activeMeshesEvaluationTime.endMonitoring();
  88171. });
  88172. }
  88173. else {
  88174. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88175. this._onBeforeActiveMeshesEvaluationObserver = null;
  88176. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88177. this._onAfterActiveMeshesEvaluationObserver = null;
  88178. }
  88179. },
  88180. enumerable: true,
  88181. configurable: true
  88182. });
  88183. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88184. /**
  88185. * Gets the perf counter used for render targets render time
  88186. */
  88187. get: function () {
  88188. return this._renderTargetsRenderTime;
  88189. },
  88190. enumerable: true,
  88191. configurable: true
  88192. });
  88193. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88194. /**
  88195. * Gets the render targets render time capture status
  88196. */
  88197. get: function () {
  88198. return this._captureRenderTargetsRenderTime;
  88199. },
  88200. /**
  88201. * Enable or disable the render targets render time capture
  88202. */
  88203. set: function (value) {
  88204. var _this = this;
  88205. if (value === this._captureRenderTargetsRenderTime) {
  88206. return;
  88207. }
  88208. this._captureRenderTargetsRenderTime = value;
  88209. if (value) {
  88210. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88211. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88212. _this._renderTargetsRenderTime.beginMonitoring();
  88213. });
  88214. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88215. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88216. _this._renderTargetsRenderTime.endMonitoring(false);
  88217. });
  88218. }
  88219. else {
  88220. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88221. this._onBeforeRenderTargetsRenderObserver = null;
  88222. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88223. this._onAfterRenderTargetsRenderObserver = null;
  88224. }
  88225. },
  88226. enumerable: true,
  88227. configurable: true
  88228. });
  88229. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88230. /**
  88231. * Gets the perf counter used for particles render time
  88232. */
  88233. get: function () {
  88234. return this._particlesRenderTime;
  88235. },
  88236. enumerable: true,
  88237. configurable: true
  88238. });
  88239. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88240. /**
  88241. * Gets the particles render time capture status
  88242. */
  88243. get: function () {
  88244. return this._captureParticlesRenderTime;
  88245. },
  88246. /**
  88247. * Enable or disable the particles render time capture
  88248. */
  88249. set: function (value) {
  88250. var _this = this;
  88251. if (value === this._captureParticlesRenderTime) {
  88252. return;
  88253. }
  88254. this._captureParticlesRenderTime = value;
  88255. if (value) {
  88256. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88257. BABYLON.Tools.StartPerformanceCounter("Particles");
  88258. _this._particlesRenderTime.beginMonitoring();
  88259. });
  88260. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88261. BABYLON.Tools.EndPerformanceCounter("Particles");
  88262. _this._particlesRenderTime.endMonitoring(false);
  88263. });
  88264. }
  88265. else {
  88266. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88267. this._onBeforeParticlesRenderingObserver = null;
  88268. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88269. this._onAfterParticlesRenderingObserver = null;
  88270. }
  88271. },
  88272. enumerable: true,
  88273. configurable: true
  88274. });
  88275. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88276. /**
  88277. * Gets the perf counter used for sprites render time
  88278. */
  88279. get: function () {
  88280. return this._spritesRenderTime;
  88281. },
  88282. enumerable: true,
  88283. configurable: true
  88284. });
  88285. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88286. /**
  88287. * Gets the sprites render time capture status
  88288. */
  88289. get: function () {
  88290. return this._captureSpritesRenderTime;
  88291. },
  88292. /**
  88293. * Enable or disable the sprites render time capture
  88294. */
  88295. set: function (value) {
  88296. var _this = this;
  88297. if (value === this._captureSpritesRenderTime) {
  88298. return;
  88299. }
  88300. this._captureSpritesRenderTime = value;
  88301. if (value) {
  88302. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88303. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88304. _this._spritesRenderTime.beginMonitoring();
  88305. });
  88306. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88307. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88308. _this._spritesRenderTime.endMonitoring(false);
  88309. });
  88310. }
  88311. else {
  88312. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88313. this._onBeforeSpritesRenderingObserver = null;
  88314. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88315. this._onAfterSpritesRenderingObserver = null;
  88316. }
  88317. },
  88318. enumerable: true,
  88319. configurable: true
  88320. });
  88321. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88322. /**
  88323. * Gets the perf counter used for physics time
  88324. */
  88325. get: function () {
  88326. return this._physicsTime;
  88327. },
  88328. enumerable: true,
  88329. configurable: true
  88330. });
  88331. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88332. /**
  88333. * Gets the physics time capture status
  88334. */
  88335. get: function () {
  88336. return this._capturePhysicsTime;
  88337. },
  88338. /**
  88339. * Enable or disable the physics time capture
  88340. */
  88341. set: function (value) {
  88342. var _this = this;
  88343. if (value === this._capturePhysicsTime) {
  88344. return;
  88345. }
  88346. this._capturePhysicsTime = value;
  88347. if (value) {
  88348. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88349. BABYLON.Tools.StartPerformanceCounter("Physics");
  88350. _this._physicsTime.beginMonitoring();
  88351. });
  88352. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88353. BABYLON.Tools.EndPerformanceCounter("Physics");
  88354. _this._physicsTime.endMonitoring();
  88355. });
  88356. }
  88357. else {
  88358. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88359. this._onBeforePhysicsObserver = null;
  88360. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88361. this._onAfterPhysicsObserver = null;
  88362. }
  88363. },
  88364. enumerable: true,
  88365. configurable: true
  88366. });
  88367. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88368. /**
  88369. * Gets the perf counter used for animations time
  88370. */
  88371. get: function () {
  88372. return this._animationsTime;
  88373. },
  88374. enumerable: true,
  88375. configurable: true
  88376. });
  88377. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88378. /**
  88379. * Gets the animations time capture status
  88380. */
  88381. get: function () {
  88382. return this._captureAnimationsTime;
  88383. },
  88384. /**
  88385. * Enable or disable the animations time capture
  88386. */
  88387. set: function (value) {
  88388. var _this = this;
  88389. if (value === this._captureAnimationsTime) {
  88390. return;
  88391. }
  88392. this._captureAnimationsTime = value;
  88393. if (value) {
  88394. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88395. _this._animationsTime.endMonitoring();
  88396. });
  88397. }
  88398. else {
  88399. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88400. this._onAfterAnimationsObserver = null;
  88401. }
  88402. },
  88403. enumerable: true,
  88404. configurable: true
  88405. });
  88406. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88407. /**
  88408. * Gets the perf counter used for frame time capture
  88409. */
  88410. get: function () {
  88411. return this._frameTime;
  88412. },
  88413. enumerable: true,
  88414. configurable: true
  88415. });
  88416. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88417. /**
  88418. * Gets the frame time capture status
  88419. */
  88420. get: function () {
  88421. return this._captureFrameTime;
  88422. },
  88423. /**
  88424. * Enable or disable the frame time capture
  88425. */
  88426. set: function (value) {
  88427. this._captureFrameTime = value;
  88428. },
  88429. enumerable: true,
  88430. configurable: true
  88431. });
  88432. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88433. /**
  88434. * Gets the perf counter used for inter-frames time capture
  88435. */
  88436. get: function () {
  88437. return this._interFrameTime;
  88438. },
  88439. enumerable: true,
  88440. configurable: true
  88441. });
  88442. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88443. /**
  88444. * Gets the inter-frames time capture status
  88445. */
  88446. get: function () {
  88447. return this._captureInterFrameTime;
  88448. },
  88449. /**
  88450. * Enable or disable the inter-frames time capture
  88451. */
  88452. set: function (value) {
  88453. this._captureInterFrameTime = value;
  88454. },
  88455. enumerable: true,
  88456. configurable: true
  88457. });
  88458. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88459. /**
  88460. * Gets the perf counter used for render time capture
  88461. */
  88462. get: function () {
  88463. return this._renderTime;
  88464. },
  88465. enumerable: true,
  88466. configurable: true
  88467. });
  88468. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88469. /**
  88470. * Gets the render time capture status
  88471. */
  88472. get: function () {
  88473. return this._captureRenderTime;
  88474. },
  88475. /**
  88476. * Enable or disable the render time capture
  88477. */
  88478. set: function (value) {
  88479. var _this = this;
  88480. if (value === this._captureRenderTime) {
  88481. return;
  88482. }
  88483. this._captureRenderTime = value;
  88484. if (value) {
  88485. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88486. _this._renderTime.beginMonitoring();
  88487. BABYLON.Tools.StartPerformanceCounter("Main render");
  88488. });
  88489. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88490. _this._renderTime.endMonitoring(false);
  88491. BABYLON.Tools.EndPerformanceCounter("Main render");
  88492. });
  88493. }
  88494. else {
  88495. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88496. this._onBeforeDrawPhaseObserver = null;
  88497. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88498. this._onAfterDrawPhaseObserver = null;
  88499. }
  88500. },
  88501. enumerable: true,
  88502. configurable: true
  88503. });
  88504. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88505. /**
  88506. * Gets the perf counter used for draw calls
  88507. */
  88508. get: function () {
  88509. return this.scene.getEngine()._drawCalls;
  88510. },
  88511. enumerable: true,
  88512. configurable: true
  88513. });
  88514. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88515. /**
  88516. * Gets the perf counter used for texture collisions
  88517. */
  88518. get: function () {
  88519. return this.scene.getEngine()._textureCollisions;
  88520. },
  88521. enumerable: true,
  88522. configurable: true
  88523. });
  88524. SceneInstrumentation.prototype.dispose = function () {
  88525. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88526. this._onAfterRenderObserver = null;
  88527. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88528. this._onBeforeActiveMeshesEvaluationObserver = null;
  88529. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88530. this._onAfterActiveMeshesEvaluationObserver = null;
  88531. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88532. this._onBeforeRenderTargetsRenderObserver = null;
  88533. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88534. this._onAfterRenderTargetsRenderObserver = null;
  88535. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88536. this._onBeforeAnimationsObserver = null;
  88537. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88538. this._onBeforeParticlesRenderingObserver = null;
  88539. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88540. this._onAfterParticlesRenderingObserver = null;
  88541. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88542. this._onBeforeSpritesRenderingObserver = null;
  88543. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88544. this._onAfterSpritesRenderingObserver = null;
  88545. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88546. this._onBeforeDrawPhaseObserver = null;
  88547. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88548. this._onAfterDrawPhaseObserver = null;
  88549. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88550. this._onBeforePhysicsObserver = null;
  88551. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88552. this._onAfterPhysicsObserver = null;
  88553. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88554. this._onAfterAnimationsObserver = null;
  88555. this.scene = null;
  88556. };
  88557. return SceneInstrumentation;
  88558. }());
  88559. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88560. })(BABYLON || (BABYLON = {}));
  88561. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88562. var BABYLON;
  88563. (function (BABYLON) {
  88564. var _TimeToken = /** @class */ (function () {
  88565. function _TimeToken() {
  88566. this._timeElapsedQueryEnded = false;
  88567. }
  88568. return _TimeToken;
  88569. }());
  88570. BABYLON._TimeToken = _TimeToken;
  88571. })(BABYLON || (BABYLON = {}));
  88572. //# sourceMappingURL=babylon.timeToken.js.map
  88573. var BABYLON;
  88574. (function (BABYLON) {
  88575. /**
  88576. * Background material defines definition.
  88577. * @ignore Mainly internal Use
  88578. */
  88579. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88580. __extends(BackgroundMaterialDefines, _super);
  88581. /**
  88582. * Constructor of the defines.
  88583. */
  88584. function BackgroundMaterialDefines() {
  88585. var _this = _super.call(this) || this;
  88586. /**
  88587. * True if the diffuse texture is in use.
  88588. */
  88589. _this.DIFFUSE = false;
  88590. /**
  88591. * The direct UV channel to use.
  88592. */
  88593. _this.DIFFUSEDIRECTUV = 0;
  88594. /**
  88595. * True if the diffuse texture is in gamma space.
  88596. */
  88597. _this.GAMMADIFFUSE = false;
  88598. /**
  88599. * True if the diffuse texture has opacity in the alpha channel.
  88600. */
  88601. _this.DIFFUSEHASALPHA = false;
  88602. /**
  88603. * True if you want the material to fade to transparent at grazing angle.
  88604. */
  88605. _this.OPACITYFRESNEL = false;
  88606. /**
  88607. * True if an extra blur needs to be added in the reflection.
  88608. */
  88609. _this.REFLECTIONBLUR = false;
  88610. /**
  88611. * True if you want the material to fade to reflection at grazing angle.
  88612. */
  88613. _this.REFLECTIONFRESNEL = false;
  88614. /**
  88615. * True if you want the material to falloff as far as you move away from the scene center.
  88616. */
  88617. _this.REFLECTIONFALLOFF = false;
  88618. /**
  88619. * False if the current Webgl implementation does not support the texture lod extension.
  88620. */
  88621. _this.TEXTURELODSUPPORT = false;
  88622. /**
  88623. * True to ensure the data are premultiplied.
  88624. */
  88625. _this.PREMULTIPLYALPHA = false;
  88626. /**
  88627. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88628. */
  88629. _this.USERGBCOLOR = false;
  88630. /**
  88631. * True to add noise in order to reduce the banding effect.
  88632. */
  88633. _this.NOISE = false;
  88634. /**
  88635. * is the reflection texture in BGR color scheme?
  88636. * Mainly used to solve a bug in ios10 video tag
  88637. */
  88638. _this.REFLECTIONBGR = false;
  88639. _this.IMAGEPROCESSING = false;
  88640. _this.VIGNETTE = false;
  88641. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88642. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88643. _this.TONEMAPPING = false;
  88644. _this.CONTRAST = false;
  88645. _this.COLORCURVES = false;
  88646. _this.COLORGRADING = false;
  88647. _this.COLORGRADING3D = false;
  88648. _this.SAMPLER3DGREENDEPTH = false;
  88649. _this.SAMPLER3DBGRMAP = false;
  88650. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88651. _this.EXPOSURE = false;
  88652. _this.GRAIN = false;
  88653. // Reflection.
  88654. _this.REFLECTION = false;
  88655. _this.REFLECTIONMAP_3D = false;
  88656. _this.REFLECTIONMAP_SPHERICAL = false;
  88657. _this.REFLECTIONMAP_PLANAR = false;
  88658. _this.REFLECTIONMAP_CUBIC = false;
  88659. _this.REFLECTIONMAP_PROJECTION = false;
  88660. _this.REFLECTIONMAP_SKYBOX = false;
  88661. _this.REFLECTIONMAP_EXPLICIT = false;
  88662. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88663. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88664. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88665. _this.INVERTCUBICMAP = false;
  88666. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88667. _this.LODINREFLECTIONALPHA = false;
  88668. _this.GAMMAREFLECTION = false;
  88669. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88670. // Default BJS.
  88671. _this.MAINUV1 = false;
  88672. _this.MAINUV2 = false;
  88673. _this.UV1 = false;
  88674. _this.UV2 = false;
  88675. _this.CLIPPLANE = false;
  88676. _this.POINTSIZE = false;
  88677. _this.FOG = false;
  88678. _this.NORMAL = false;
  88679. _this.NUM_BONE_INFLUENCERS = 0;
  88680. _this.BonesPerMesh = 0;
  88681. _this.INSTANCES = false;
  88682. _this.SHADOWFLOAT = false;
  88683. _this.rebuild();
  88684. return _this;
  88685. }
  88686. return BackgroundMaterialDefines;
  88687. }(BABYLON.MaterialDefines));
  88688. /**
  88689. * Background material used to create an efficient environement around your scene.
  88690. */
  88691. var BackgroundMaterial = /** @class */ (function (_super) {
  88692. __extends(BackgroundMaterial, _super);
  88693. /**
  88694. * Instantiates a Background Material in the given scene
  88695. * @param name The friendly name of the material
  88696. * @param scene The scene to add the material to
  88697. */
  88698. function BackgroundMaterial(name, scene) {
  88699. var _this = _super.call(this, name, scene) || this;
  88700. /**
  88701. * Key light Color (multiply against the R channel of the environement texture)
  88702. */
  88703. _this.primaryColor = BABYLON.Color3.White();
  88704. /**
  88705. * Key light Level (allowing HDR output of the background)
  88706. */
  88707. _this.primaryLevel = 1;
  88708. /**
  88709. * Secondary light Color (multiply against the G channel of the environement texture)
  88710. */
  88711. _this.secondaryColor = BABYLON.Color3.Gray();
  88712. /**
  88713. * Secondary light Level (allowing HDR output of the background)
  88714. */
  88715. _this.secondaryLevel = 1;
  88716. /**
  88717. * Tertiary light Color (multiply against the B channel of the environement texture)
  88718. */
  88719. _this.tertiaryColor = BABYLON.Color3.Black();
  88720. /**
  88721. * Tertiary light Level (allowing HDR output of the background)
  88722. */
  88723. _this.tertiaryLevel = 1;
  88724. /**
  88725. * Reflection Texture used in the material.
  88726. * Should be author in a specific way for the best result (refer to the documentation).
  88727. */
  88728. _this.reflectionTexture = null;
  88729. /**
  88730. * Reflection Texture level of blur.
  88731. *
  88732. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88733. * texture twice.
  88734. */
  88735. _this.reflectionBlur = 0;
  88736. /**
  88737. * Diffuse Texture used in the material.
  88738. * Should be author in a specific way for the best result (refer to the documentation).
  88739. */
  88740. _this.diffuseTexture = null;
  88741. _this._shadowLights = null;
  88742. /**
  88743. * Specify the list of lights casting shadow on the material.
  88744. * All scene shadow lights will be included if null.
  88745. */
  88746. _this.shadowLights = null;
  88747. /**
  88748. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88749. * soft lighting on the background.
  88750. */
  88751. _this.shadowBlurScale = 1;
  88752. /**
  88753. * Helps adjusting the shadow to a softer level if required.
  88754. * 0 means black shadows and 1 means no shadows.
  88755. */
  88756. _this.shadowLevel = 0;
  88757. /**
  88758. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88759. * It is usually zero but might be interesting to modify according to your setup.
  88760. */
  88761. _this.sceneCenter = BABYLON.Vector3.Zero();
  88762. /**
  88763. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88764. * This helps ensuring a nice transition when the camera goes under the ground.
  88765. */
  88766. _this.opacityFresnel = true;
  88767. /**
  88768. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88769. * This helps adding a mirror texture on the ground.
  88770. */
  88771. _this.reflectionFresnel = false;
  88772. /**
  88773. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88774. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88775. */
  88776. _this.reflectionFalloffDistance = 0.0;
  88777. /**
  88778. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88779. */
  88780. _this.reflectionAmount = 1.0;
  88781. /**
  88782. * This specifies the weight of the reflection at grazing angle.
  88783. */
  88784. _this.reflectionReflectance0 = 0.05;
  88785. /**
  88786. * This specifies the weight of the reflection at a perpendicular point of view.
  88787. */
  88788. _this.reflectionReflectance90 = 0.5;
  88789. /**
  88790. * Helps to directly use the maps channels instead of their level.
  88791. */
  88792. _this.useRGBColor = true;
  88793. /**
  88794. * This helps reducing the banding effect that could occur on the background.
  88795. */
  88796. _this.enableNoise = false;
  88797. _this._fovMultiplier = 1.0;
  88798. /**
  88799. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88800. * @type {boolean}
  88801. */
  88802. _this.useEquirectangularFOV = false;
  88803. _this._maxSimultaneousLights = 4;
  88804. /**
  88805. * Number of Simultaneous lights allowed on the material.
  88806. */
  88807. _this.maxSimultaneousLights = 4;
  88808. /**
  88809. * Keep track of the image processing observer to allow dispose and replace.
  88810. */
  88811. _this._imageProcessingObserver = null;
  88812. /**
  88813. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88814. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88815. */
  88816. _this.switchToBGR = false;
  88817. // Temp values kept as cache in the material.
  88818. _this._renderTargets = new BABYLON.SmartArray(16);
  88819. _this._reflectionControls = BABYLON.Vector4.Zero();
  88820. // Setup the default processing configuration to the scene.
  88821. _this._attachImageProcessingConfiguration(null);
  88822. _this.getRenderTargetTextures = function () {
  88823. _this._renderTargets.reset();
  88824. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88825. _this._renderTargets.push(_this._diffuseTexture);
  88826. }
  88827. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88828. _this._renderTargets.push(_this._reflectionTexture);
  88829. }
  88830. return _this._renderTargets;
  88831. };
  88832. return _this;
  88833. }
  88834. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88835. /**
  88836. * Sets the reflection reflectance fresnel values according to the default standard
  88837. * empirically know to work well :-)
  88838. */
  88839. set: function (value) {
  88840. var reflectionWeight = value;
  88841. if (reflectionWeight < 0.5) {
  88842. reflectionWeight = reflectionWeight * 2.0;
  88843. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88844. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88845. }
  88846. else {
  88847. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88848. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88849. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88850. }
  88851. },
  88852. enumerable: true,
  88853. configurable: true
  88854. });
  88855. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88856. /**
  88857. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88858. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88859. * Recommended to be keep at 1.0 except for special cases.
  88860. */
  88861. get: function () {
  88862. return this._fovMultiplier;
  88863. },
  88864. set: function (value) {
  88865. if (isNaN(value)) {
  88866. value = 1.0;
  88867. }
  88868. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88869. },
  88870. enumerable: true,
  88871. configurable: true
  88872. });
  88873. /**
  88874. * Attaches a new image processing configuration to the PBR Material.
  88875. * @param configuration (if null the scene configuration will be use)
  88876. */
  88877. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88878. var _this = this;
  88879. if (configuration === this._imageProcessingConfiguration) {
  88880. return;
  88881. }
  88882. // Detaches observer.
  88883. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88884. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88885. }
  88886. // Pick the scene configuration if needed.
  88887. if (!configuration) {
  88888. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88889. }
  88890. else {
  88891. this._imageProcessingConfiguration = configuration;
  88892. }
  88893. // Attaches observer.
  88894. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88895. _this._markAllSubMeshesAsImageProcessingDirty();
  88896. });
  88897. };
  88898. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88899. /**
  88900. * Gets the image processing configuration used either in this material.
  88901. */
  88902. get: function () {
  88903. return this._imageProcessingConfiguration;
  88904. },
  88905. /**
  88906. * Sets the Default image processing configuration used either in the this material.
  88907. *
  88908. * If sets to null, the scene one is in use.
  88909. */
  88910. set: function (value) {
  88911. this._attachImageProcessingConfiguration(value);
  88912. // Ensure the effect will be rebuilt.
  88913. this._markAllSubMeshesAsTexturesDirty();
  88914. },
  88915. enumerable: true,
  88916. configurable: true
  88917. });
  88918. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88919. /**
  88920. * Gets wether the color curves effect is enabled.
  88921. */
  88922. get: function () {
  88923. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88924. },
  88925. /**
  88926. * Sets wether the color curves effect is enabled.
  88927. */
  88928. set: function (value) {
  88929. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88930. },
  88931. enumerable: true,
  88932. configurable: true
  88933. });
  88934. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88935. /**
  88936. * Gets wether the color grading effect is enabled.
  88937. */
  88938. get: function () {
  88939. return this.imageProcessingConfiguration.colorGradingEnabled;
  88940. },
  88941. /**
  88942. * Gets wether the color grading effect is enabled.
  88943. */
  88944. set: function (value) {
  88945. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88946. },
  88947. enumerable: true,
  88948. configurable: true
  88949. });
  88950. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88951. /**
  88952. * Gets wether tonemapping is enabled or not.
  88953. */
  88954. get: function () {
  88955. return this._imageProcessingConfiguration.toneMappingEnabled;
  88956. },
  88957. /**
  88958. * Sets wether tonemapping is enabled or not
  88959. */
  88960. set: function (value) {
  88961. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88962. },
  88963. enumerable: true,
  88964. configurable: true
  88965. });
  88966. ;
  88967. ;
  88968. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88969. /**
  88970. * The camera exposure used on this material.
  88971. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88972. * This corresponds to a photographic exposure.
  88973. */
  88974. get: function () {
  88975. return this._imageProcessingConfiguration.exposure;
  88976. },
  88977. /**
  88978. * The camera exposure used on this material.
  88979. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88980. * This corresponds to a photographic exposure.
  88981. */
  88982. set: function (value) {
  88983. this._imageProcessingConfiguration.exposure = value;
  88984. },
  88985. enumerable: true,
  88986. configurable: true
  88987. });
  88988. ;
  88989. ;
  88990. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88991. /**
  88992. * Gets The camera contrast used on this material.
  88993. */
  88994. get: function () {
  88995. return this._imageProcessingConfiguration.contrast;
  88996. },
  88997. /**
  88998. * Sets The camera contrast used on this material.
  88999. */
  89000. set: function (value) {
  89001. this._imageProcessingConfiguration.contrast = value;
  89002. },
  89003. enumerable: true,
  89004. configurable: true
  89005. });
  89006. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89007. /**
  89008. * Gets the Color Grading 2D Lookup Texture.
  89009. */
  89010. get: function () {
  89011. return this._imageProcessingConfiguration.colorGradingTexture;
  89012. },
  89013. /**
  89014. * Sets the Color Grading 2D Lookup Texture.
  89015. */
  89016. set: function (value) {
  89017. this.imageProcessingConfiguration.colorGradingTexture = value;
  89018. },
  89019. enumerable: true,
  89020. configurable: true
  89021. });
  89022. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89023. /**
  89024. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89025. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89026. * 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;
  89027. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89028. */
  89029. get: function () {
  89030. return this.imageProcessingConfiguration.colorCurves;
  89031. },
  89032. /**
  89033. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89034. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89035. * 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;
  89036. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89037. */
  89038. set: function (value) {
  89039. this.imageProcessingConfiguration.colorCurves = value;
  89040. },
  89041. enumerable: true,
  89042. configurable: true
  89043. });
  89044. /**
  89045. * The entire material has been created in order to prevent overdraw.
  89046. * @returns false
  89047. */
  89048. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89049. return true;
  89050. };
  89051. /**
  89052. * The entire material has been created in order to prevent overdraw.
  89053. * @returns true if blending is enable
  89054. */
  89055. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89056. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89057. };
  89058. /**
  89059. * Checks wether the material is ready to be rendered for a given mesh.
  89060. * @param mesh The mesh to render
  89061. * @param subMesh The submesh to check against
  89062. * @param useInstances Specify wether or not the material is used with instances
  89063. * @returns true if all the dependencies are ready (Textures, Effects...)
  89064. */
  89065. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89066. var _this = this;
  89067. if (useInstances === void 0) { useInstances = false; }
  89068. if (subMesh.effect && this.isFrozen) {
  89069. if (this._wasPreviouslyReady) {
  89070. return true;
  89071. }
  89072. }
  89073. if (!subMesh._materialDefines) {
  89074. subMesh._materialDefines = new BackgroundMaterialDefines();
  89075. }
  89076. var scene = this.getScene();
  89077. var defines = subMesh._materialDefines;
  89078. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89079. if (defines._renderId === scene.getRenderId()) {
  89080. return true;
  89081. }
  89082. }
  89083. var engine = scene.getEngine();
  89084. // Lights
  89085. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89086. defines._needNormals = true;
  89087. // Textures
  89088. if (defines._areTexturesDirty) {
  89089. defines._needUVs = false;
  89090. if (scene.texturesEnabled) {
  89091. if (scene.getEngine().getCaps().textureLOD) {
  89092. defines.TEXTURELODSUPPORT = true;
  89093. }
  89094. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89095. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89096. return false;
  89097. }
  89098. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89099. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89100. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89101. defines.OPACITYFRESNEL = this._opacityFresnel;
  89102. }
  89103. else {
  89104. defines.DIFFUSE = false;
  89105. defines.DIFFUSEHASALPHA = false;
  89106. defines.GAMMADIFFUSE = false;
  89107. defines.OPACITYFRESNEL = false;
  89108. }
  89109. var reflectionTexture = this._reflectionTexture;
  89110. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89111. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89112. return false;
  89113. }
  89114. defines.REFLECTION = true;
  89115. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89116. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89117. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89118. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89119. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89120. defines.REFLECTIONBGR = this.switchToBGR;
  89121. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89122. defines.INVERTCUBICMAP = true;
  89123. }
  89124. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89125. switch (reflectionTexture.coordinatesMode) {
  89126. case BABYLON.Texture.CUBIC_MODE:
  89127. case BABYLON.Texture.INVCUBIC_MODE:
  89128. defines.REFLECTIONMAP_CUBIC = true;
  89129. break;
  89130. case BABYLON.Texture.EXPLICIT_MODE:
  89131. defines.REFLECTIONMAP_EXPLICIT = true;
  89132. break;
  89133. case BABYLON.Texture.PLANAR_MODE:
  89134. defines.REFLECTIONMAP_PLANAR = true;
  89135. break;
  89136. case BABYLON.Texture.PROJECTION_MODE:
  89137. defines.REFLECTIONMAP_PROJECTION = true;
  89138. break;
  89139. case BABYLON.Texture.SKYBOX_MODE:
  89140. defines.REFLECTIONMAP_SKYBOX = true;
  89141. break;
  89142. case BABYLON.Texture.SPHERICAL_MODE:
  89143. defines.REFLECTIONMAP_SPHERICAL = true;
  89144. break;
  89145. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89146. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89147. break;
  89148. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89149. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89150. break;
  89151. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89152. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89153. break;
  89154. }
  89155. if (this.reflectionFresnel) {
  89156. defines.REFLECTIONFRESNEL = true;
  89157. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89158. this._reflectionControls.x = this.reflectionAmount;
  89159. this._reflectionControls.y = this.reflectionReflectance0;
  89160. this._reflectionControls.z = this.reflectionReflectance90;
  89161. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89162. }
  89163. else {
  89164. defines.REFLECTIONFRESNEL = false;
  89165. defines.REFLECTIONFALLOFF = false;
  89166. }
  89167. }
  89168. else {
  89169. defines.REFLECTION = false;
  89170. defines.REFLECTIONFALLOFF = false;
  89171. defines.REFLECTIONBLUR = false;
  89172. defines.REFLECTIONMAP_3D = false;
  89173. defines.REFLECTIONMAP_SPHERICAL = false;
  89174. defines.REFLECTIONMAP_PLANAR = false;
  89175. defines.REFLECTIONMAP_CUBIC = false;
  89176. defines.REFLECTIONMAP_PROJECTION = false;
  89177. defines.REFLECTIONMAP_SKYBOX = false;
  89178. defines.REFLECTIONMAP_EXPLICIT = false;
  89179. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89180. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89181. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89182. defines.INVERTCUBICMAP = false;
  89183. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89184. defines.LODINREFLECTIONALPHA = false;
  89185. defines.GAMMAREFLECTION = false;
  89186. }
  89187. }
  89188. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89189. defines.USERGBCOLOR = this._useRGBColor;
  89190. defines.NOISE = this._enableNoise;
  89191. }
  89192. if (defines._areImageProcessingDirty) {
  89193. if (!this._imageProcessingConfiguration.isReady()) {
  89194. return false;
  89195. }
  89196. this._imageProcessingConfiguration.prepareDefines(defines);
  89197. }
  89198. // Misc.
  89199. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89200. // Values that need to be evaluated on every frame
  89201. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89202. // Attribs
  89203. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89204. if (mesh) {
  89205. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89206. mesh.createNormals(true);
  89207. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89208. }
  89209. }
  89210. }
  89211. // Get correct effect
  89212. if (defines.isDirty) {
  89213. defines.markAsProcessed();
  89214. scene.resetCachedMaterial();
  89215. // Fallbacks
  89216. var fallbacks = new BABYLON.EffectFallbacks();
  89217. if (defines.FOG) {
  89218. fallbacks.addFallback(0, "FOG");
  89219. }
  89220. if (defines.POINTSIZE) {
  89221. fallbacks.addFallback(1, "POINTSIZE");
  89222. }
  89223. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89224. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89225. fallbacks.addCPUSkinningFallback(0, mesh);
  89226. }
  89227. //Attributes
  89228. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89229. if (defines.NORMAL) {
  89230. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89231. }
  89232. if (defines.UV1) {
  89233. attribs.push(BABYLON.VertexBuffer.UVKind);
  89234. }
  89235. if (defines.UV2) {
  89236. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89237. }
  89238. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89239. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89240. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89241. "vFogInfos", "vFogColor", "pointSize",
  89242. "vClipPlane", "mBones",
  89243. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89244. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89245. "shadowLevel", "alpha",
  89246. "vBackgroundCenter", "vReflectionControl",
  89247. "vDiffuseInfos", "diffuseMatrix",
  89248. ];
  89249. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89250. var uniformBuffers = ["Material", "Scene"];
  89251. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89252. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89253. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89254. uniformsNames: uniforms,
  89255. uniformBuffersNames: uniformBuffers,
  89256. samplers: samplers,
  89257. defines: defines,
  89258. maxSimultaneousLights: this._maxSimultaneousLights
  89259. });
  89260. var onCompiled = function (effect) {
  89261. if (_this.onCompiled) {
  89262. _this.onCompiled(effect);
  89263. }
  89264. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89265. };
  89266. var join = defines.toString();
  89267. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89268. attributes: attribs,
  89269. uniformsNames: uniforms,
  89270. uniformBuffersNames: uniformBuffers,
  89271. samplers: samplers,
  89272. defines: join,
  89273. fallbacks: fallbacks,
  89274. onCompiled: onCompiled,
  89275. onError: this.onError,
  89276. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89277. }, engine), defines);
  89278. this.buildUniformLayout();
  89279. }
  89280. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89281. return false;
  89282. }
  89283. defines._renderId = scene.getRenderId();
  89284. this._wasPreviouslyReady = true;
  89285. return true;
  89286. };
  89287. /**
  89288. * Build the uniform buffer used in the material.
  89289. */
  89290. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89291. // Order is important !
  89292. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89293. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89294. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89295. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89296. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89297. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89298. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89299. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89300. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89301. this._uniformBuffer.addUniform("pointSize", 1);
  89302. this._uniformBuffer.addUniform("shadowLevel", 1);
  89303. this._uniformBuffer.addUniform("alpha", 1);
  89304. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89305. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89306. this._uniformBuffer.create();
  89307. };
  89308. /**
  89309. * Unbind the material.
  89310. */
  89311. BackgroundMaterial.prototype.unbind = function () {
  89312. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89313. this._uniformBuffer.setTexture("diffuseSampler", null);
  89314. }
  89315. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89316. this._uniformBuffer.setTexture("reflectionSampler", null);
  89317. }
  89318. _super.prototype.unbind.call(this);
  89319. };
  89320. /**
  89321. * Bind only the world matrix to the material.
  89322. * @param world The world matrix to bind.
  89323. */
  89324. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89325. this._activeEffect.setMatrix("world", world);
  89326. };
  89327. /**
  89328. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89329. * @param world The world matrix to bind.
  89330. * @param subMesh The submesh to bind for.
  89331. */
  89332. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89333. var scene = this.getScene();
  89334. var defines = subMesh._materialDefines;
  89335. if (!defines) {
  89336. return;
  89337. }
  89338. var effect = subMesh.effect;
  89339. if (!effect) {
  89340. return;
  89341. }
  89342. this._activeEffect = effect;
  89343. // Matrices
  89344. this.bindOnlyWorldMatrix(world);
  89345. // Bones
  89346. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89347. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89348. if (mustRebind) {
  89349. this._uniformBuffer.bindToEffect(effect, "Material");
  89350. this.bindViewProjection(effect);
  89351. var reflectionTexture = this._reflectionTexture;
  89352. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89353. // Texture uniforms
  89354. if (scene.texturesEnabled) {
  89355. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89356. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89357. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89358. }
  89359. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89360. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89361. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89362. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89363. }
  89364. }
  89365. if (this.shadowLevel > 0) {
  89366. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89367. }
  89368. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89369. // Point size
  89370. if (this.pointsCloud) {
  89371. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89372. }
  89373. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89374. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89375. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89376. }
  89377. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89378. // Textures
  89379. if (scene.texturesEnabled) {
  89380. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89381. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89382. }
  89383. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89384. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89385. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89386. }
  89387. else if (!defines.REFLECTIONBLUR) {
  89388. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89389. }
  89390. else {
  89391. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89392. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89393. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89394. }
  89395. if (defines.REFLECTIONFRESNEL) {
  89396. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89397. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89398. }
  89399. }
  89400. }
  89401. // Clip plane
  89402. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89403. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89404. }
  89405. if (mustRebind || !this.isFrozen) {
  89406. if (scene.lightsEnabled) {
  89407. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89408. }
  89409. // View
  89410. this.bindView(effect);
  89411. // Fog
  89412. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89413. // image processing
  89414. this._imageProcessingConfiguration.bind(this._activeEffect);
  89415. }
  89416. this._uniformBuffer.update();
  89417. this._afterBind(mesh);
  89418. };
  89419. /**
  89420. * Dispose the material.
  89421. * @param forceDisposeEffect Force disposal of the associated effect.
  89422. * @param forceDisposeTextures Force disposal of the associated textures.
  89423. */
  89424. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89425. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89426. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89427. if (forceDisposeTextures) {
  89428. if (this.diffuseTexture) {
  89429. this.diffuseTexture.dispose();
  89430. }
  89431. if (this.reflectionTexture) {
  89432. this.reflectionTexture.dispose();
  89433. }
  89434. }
  89435. this._renderTargets.dispose();
  89436. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89437. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89438. }
  89439. _super.prototype.dispose.call(this, forceDisposeEffect);
  89440. };
  89441. /**
  89442. * Clones the material.
  89443. * @param name The cloned name.
  89444. * @returns The cloned material.
  89445. */
  89446. BackgroundMaterial.prototype.clone = function (name) {
  89447. var _this = this;
  89448. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89449. };
  89450. /**
  89451. * Serializes the current material to its JSON representation.
  89452. * @returns The JSON representation.
  89453. */
  89454. BackgroundMaterial.prototype.serialize = function () {
  89455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89456. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89457. return serializationObject;
  89458. };
  89459. /**
  89460. * Gets the class name of the material
  89461. * @returns "BackgroundMaterial"
  89462. */
  89463. BackgroundMaterial.prototype.getClassName = function () {
  89464. return "BackgroundMaterial";
  89465. };
  89466. /**
  89467. * Parse a JSON input to create back a background material.
  89468. * @param source The JSON data to parse
  89469. * @param scene The scene to create the parsed material in
  89470. * @param rootUrl The root url of the assets the material depends upon
  89471. * @returns the instantiated BackgroundMaterial.
  89472. */
  89473. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89474. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89475. };
  89476. /**
  89477. * Standard reflectance value at parallel view angle.
  89478. */
  89479. BackgroundMaterial.StandardReflectance0 = 0.05;
  89480. /**
  89481. * Standard reflectance value at grazing angle.
  89482. */
  89483. BackgroundMaterial.StandardReflectance90 = 0.5;
  89484. __decorate([
  89485. BABYLON.serializeAsColor3()
  89486. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89487. __decorate([
  89488. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89489. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89490. __decorate([
  89491. BABYLON.serialize()
  89492. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89493. __decorate([
  89494. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89495. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89496. __decorate([
  89497. BABYLON.serializeAsColor3()
  89498. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89499. __decorate([
  89500. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89501. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89502. __decorate([
  89503. BABYLON.serialize()
  89504. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89505. __decorate([
  89506. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89507. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89508. __decorate([
  89509. BABYLON.serializeAsColor3()
  89510. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89511. __decorate([
  89512. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89513. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89514. __decorate([
  89515. BABYLON.serialize()
  89516. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89517. __decorate([
  89518. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89519. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89520. __decorate([
  89521. BABYLON.serializeAsTexture()
  89522. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89523. __decorate([
  89524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89525. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89526. __decorate([
  89527. BABYLON.serialize()
  89528. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89529. __decorate([
  89530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89531. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89532. __decorate([
  89533. BABYLON.serializeAsTexture()
  89534. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89535. __decorate([
  89536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89537. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89538. __decorate([
  89539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89540. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89541. __decorate([
  89542. BABYLON.serialize()
  89543. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89544. __decorate([
  89545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89546. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89547. __decorate([
  89548. BABYLON.serialize()
  89549. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89550. __decorate([
  89551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89552. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89553. __decorate([
  89554. BABYLON.serializeAsVector3()
  89555. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89556. __decorate([
  89557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89558. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89559. __decorate([
  89560. BABYLON.serialize()
  89561. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89562. __decorate([
  89563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89564. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89565. __decorate([
  89566. BABYLON.serialize()
  89567. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89568. __decorate([
  89569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89570. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89571. __decorate([
  89572. BABYLON.serialize()
  89573. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89574. __decorate([
  89575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89576. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89577. __decorate([
  89578. BABYLON.serialize()
  89579. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89580. __decorate([
  89581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89582. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89583. __decorate([
  89584. BABYLON.serialize()
  89585. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89586. __decorate([
  89587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89588. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89589. __decorate([
  89590. BABYLON.serialize()
  89591. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89592. __decorate([
  89593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89594. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89595. __decorate([
  89596. BABYLON.serialize()
  89597. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89598. __decorate([
  89599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89600. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89601. __decorate([
  89602. BABYLON.serialize()
  89603. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89604. __decorate([
  89605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89606. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89607. __decorate([
  89608. BABYLON.serialize()
  89609. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89610. __decorate([
  89611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89612. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89613. __decorate([
  89614. BABYLON.serializeAsImageProcessingConfiguration()
  89615. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89616. return BackgroundMaterial;
  89617. }(BABYLON.PushMaterial));
  89618. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89619. })(BABYLON || (BABYLON = {}));
  89620. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89621. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89622. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89623. s = arguments[i];
  89624. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89625. t[p] = s[p];
  89626. }
  89627. return t;
  89628. };
  89629. var BABYLON;
  89630. (function (BABYLON) {
  89631. /**
  89632. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89633. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89634. * It also helps with the default setup of your imageProcessing configuration.
  89635. */
  89636. var EnvironmentHelper = /** @class */ (function () {
  89637. /**
  89638. * constructor
  89639. * @param options
  89640. * @param scene The scene to add the material to
  89641. */
  89642. function EnvironmentHelper(options, scene) {
  89643. var _this = this;
  89644. this._errorHandler = function (message, exception) {
  89645. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  89646. };
  89647. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89648. this._scene = scene;
  89649. this.onErrorObservable = new BABYLON.Observable();
  89650. this._setupBackground();
  89651. this._setupImageProcessing();
  89652. }
  89653. /**
  89654. * Creates the default options for the helper.
  89655. */
  89656. EnvironmentHelper._getDefaultOptions = function () {
  89657. return {
  89658. createGround: true,
  89659. groundSize: 15,
  89660. groundTexture: this._groundTextureCDNUrl,
  89661. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89662. groundOpacity: 0.9,
  89663. enableGroundShadow: true,
  89664. groundShadowLevel: 0.5,
  89665. enableGroundMirror: false,
  89666. groundMirrorSizeRatio: 0.3,
  89667. groundMirrorBlurKernel: 64,
  89668. groundMirrorAmount: 1,
  89669. groundMirrorFresnelWeight: 1,
  89670. groundMirrorFallOffDistance: 0,
  89671. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89672. groundYBias: 0.00001,
  89673. createSkybox: true,
  89674. skyboxSize: 20,
  89675. skyboxTexture: this._skyboxTextureCDNUrl,
  89676. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89677. backgroundYRotation: 0,
  89678. sizeAuto: true,
  89679. rootPosition: BABYLON.Vector3.Zero(),
  89680. setupImageProcessing: true,
  89681. environmentTexture: this._environmentTextureCDNUrl,
  89682. cameraExposure: 0.8,
  89683. cameraContrast: 1.2,
  89684. toneMappingEnabled: true,
  89685. };
  89686. };
  89687. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89688. /**
  89689. * Gets the root mesh created by the helper.
  89690. */
  89691. get: function () {
  89692. return this._rootMesh;
  89693. },
  89694. enumerable: true,
  89695. configurable: true
  89696. });
  89697. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89698. /**
  89699. * Gets the skybox created by the helper.
  89700. */
  89701. get: function () {
  89702. return this._skybox;
  89703. },
  89704. enumerable: true,
  89705. configurable: true
  89706. });
  89707. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89708. /**
  89709. * Gets the skybox texture created by the helper.
  89710. */
  89711. get: function () {
  89712. return this._skyboxTexture;
  89713. },
  89714. enumerable: true,
  89715. configurable: true
  89716. });
  89717. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89718. /**
  89719. * Gets the skybox material created by the helper.
  89720. */
  89721. get: function () {
  89722. return this._skyboxMaterial;
  89723. },
  89724. enumerable: true,
  89725. configurable: true
  89726. });
  89727. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89728. /**
  89729. * Gets the ground mesh created by the helper.
  89730. */
  89731. get: function () {
  89732. return this._ground;
  89733. },
  89734. enumerable: true,
  89735. configurable: true
  89736. });
  89737. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89738. /**
  89739. * Gets the ground texture created by the helper.
  89740. */
  89741. get: function () {
  89742. return this._groundTexture;
  89743. },
  89744. enumerable: true,
  89745. configurable: true
  89746. });
  89747. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89748. /**
  89749. * Gets the ground mirror created by the helper.
  89750. */
  89751. get: function () {
  89752. return this._groundMirror;
  89753. },
  89754. enumerable: true,
  89755. configurable: true
  89756. });
  89757. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89758. /**
  89759. * Gets the ground mirror render list to helps pushing the meshes
  89760. * you wish in the ground reflection.
  89761. */
  89762. get: function () {
  89763. if (this._groundMirror) {
  89764. return this._groundMirror.renderList;
  89765. }
  89766. return null;
  89767. },
  89768. enumerable: true,
  89769. configurable: true
  89770. });
  89771. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89772. /**
  89773. * Gets the ground material created by the helper.
  89774. */
  89775. get: function () {
  89776. return this._groundMaterial;
  89777. },
  89778. enumerable: true,
  89779. configurable: true
  89780. });
  89781. /**
  89782. * Updates the background according to the new options
  89783. * @param options
  89784. */
  89785. EnvironmentHelper.prototype.updateOptions = function (options) {
  89786. var newOptions = __assign({}, this._options, options);
  89787. if (this._ground && !newOptions.createGround) {
  89788. this._ground.dispose();
  89789. this._ground = null;
  89790. }
  89791. if (this._groundMaterial && !newOptions.createGround) {
  89792. this._groundMaterial.dispose();
  89793. this._groundMaterial = null;
  89794. }
  89795. if (this._groundTexture) {
  89796. if (this._options.groundTexture != newOptions.groundTexture) {
  89797. this._groundTexture.dispose();
  89798. this._groundTexture = null;
  89799. }
  89800. }
  89801. if (this._skybox && !newOptions.createSkybox) {
  89802. this._skybox.dispose();
  89803. this._skybox = null;
  89804. }
  89805. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89806. this._skyboxMaterial.dispose();
  89807. this._skyboxMaterial = null;
  89808. }
  89809. if (this._skyboxTexture) {
  89810. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89811. this._skyboxTexture.dispose();
  89812. this._skyboxTexture = null;
  89813. }
  89814. }
  89815. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89816. this._groundMirror.dispose();
  89817. this._groundMirror = null;
  89818. }
  89819. if (this._scene.environmentTexture) {
  89820. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89821. this._scene.environmentTexture.dispose();
  89822. }
  89823. }
  89824. this._options = newOptions;
  89825. this._setupBackground();
  89826. this._setupImageProcessing();
  89827. };
  89828. /**
  89829. * Sets the primary color of all the available elements.
  89830. * @param color
  89831. */
  89832. EnvironmentHelper.prototype.setMainColor = function (color) {
  89833. if (this.groundMaterial) {
  89834. this.groundMaterial.primaryColor = color;
  89835. }
  89836. if (this.skyboxMaterial) {
  89837. this.skyboxMaterial.primaryColor = color;
  89838. }
  89839. if (this.groundMirror) {
  89840. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89841. }
  89842. };
  89843. /**
  89844. * Setup the image processing according to the specified options.
  89845. */
  89846. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89847. if (this._options.setupImageProcessing) {
  89848. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89849. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89850. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89851. this._setupEnvironmentTexture();
  89852. }
  89853. };
  89854. /**
  89855. * Setup the environment texture according to the specified options.
  89856. */
  89857. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89858. if (this._scene.environmentTexture) {
  89859. return;
  89860. }
  89861. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89862. this._scene.environmentTexture = this._options.environmentTexture;
  89863. return;
  89864. }
  89865. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89866. this._scene.environmentTexture = environmentTexture;
  89867. };
  89868. /**
  89869. * Setup the background according to the specified options.
  89870. */
  89871. EnvironmentHelper.prototype._setupBackground = function () {
  89872. if (!this._rootMesh) {
  89873. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89874. }
  89875. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89876. var sceneSize = this._getSceneSize();
  89877. if (this._options.createGround) {
  89878. this._setupGround(sceneSize);
  89879. this._setupGroundMaterial();
  89880. this._setupGroundDiffuseTexture();
  89881. if (this._options.enableGroundMirror) {
  89882. this._setupGroundMirrorTexture(sceneSize);
  89883. }
  89884. this._setupMirrorInGroundMaterial();
  89885. }
  89886. if (this._options.createSkybox) {
  89887. this._setupSkybox(sceneSize);
  89888. this._setupSkyboxMaterial();
  89889. this._setupSkyboxReflectionTexture();
  89890. }
  89891. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89892. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89893. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89894. };
  89895. /**
  89896. * Get the scene sizes according to the setup.
  89897. */
  89898. EnvironmentHelper.prototype._getSceneSize = function () {
  89899. var _this = this;
  89900. var groundSize = this._options.groundSize;
  89901. var skyboxSize = this._options.skyboxSize;
  89902. var rootPosition = this._options.rootPosition;
  89903. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89904. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89905. }
  89906. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89907. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89908. });
  89909. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89910. if (this._options.sizeAuto) {
  89911. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89912. this._scene.activeCamera.upperRadiusLimit) {
  89913. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89914. skyboxSize = groundSize;
  89915. }
  89916. var sceneDiagonalLenght = sceneDiagonal.length();
  89917. if (sceneDiagonalLenght > groundSize) {
  89918. groundSize = sceneDiagonalLenght * 2;
  89919. skyboxSize = groundSize;
  89920. }
  89921. // 10 % bigger.
  89922. groundSize *= 1.1;
  89923. skyboxSize *= 1.5;
  89924. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89925. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89926. }
  89927. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89928. };
  89929. /**
  89930. * Setup the ground according to the specified options.
  89931. */
  89932. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89933. var _this = this;
  89934. if (!this._ground) {
  89935. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89936. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89937. this._ground.parent = this._rootMesh;
  89938. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89939. }
  89940. this._ground.receiveShadows = this._options.enableGroundShadow;
  89941. };
  89942. /**
  89943. * Setup the ground material according to the specified options.
  89944. */
  89945. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89946. if (!this._groundMaterial) {
  89947. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89948. }
  89949. this._groundMaterial.alpha = this._options.groundOpacity;
  89950. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89951. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89952. this._groundMaterial.primaryLevel = 1;
  89953. this._groundMaterial.primaryColor = this._options.groundColor;
  89954. this._groundMaterial.secondaryLevel = 0;
  89955. this._groundMaterial.tertiaryLevel = 0;
  89956. this._groundMaterial.useRGBColor = false;
  89957. this._groundMaterial.enableNoise = true;
  89958. if (this._ground) {
  89959. this._ground.material = this._groundMaterial;
  89960. }
  89961. };
  89962. /**
  89963. * Setup the ground diffuse texture according to the specified options.
  89964. */
  89965. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89966. if (!this._groundMaterial) {
  89967. return;
  89968. }
  89969. if (this._groundTexture) {
  89970. return;
  89971. }
  89972. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89973. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89974. return;
  89975. }
  89976. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89977. diffuseTexture.gammaSpace = false;
  89978. diffuseTexture.hasAlpha = true;
  89979. this._groundMaterial.diffuseTexture = diffuseTexture;
  89980. };
  89981. /**
  89982. * Setup the ground mirror texture according to the specified options.
  89983. */
  89984. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89985. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89986. if (!this._groundMirror) {
  89987. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89988. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89989. this._groundMirror.anisotropicFilteringLevel = 1;
  89990. this._groundMirror.wrapU = wrapping;
  89991. this._groundMirror.wrapV = wrapping;
  89992. this._groundMirror.gammaSpace = false;
  89993. if (this._groundMirror.renderList) {
  89994. for (var i = 0; i < this._scene.meshes.length; i++) {
  89995. var mesh = this._scene.meshes[i];
  89996. if (mesh !== this._ground &&
  89997. mesh !== this._skybox &&
  89998. mesh !== this._rootMesh) {
  89999. this._groundMirror.renderList.push(mesh);
  90000. }
  90001. }
  90002. }
  90003. }
  90004. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90005. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90006. };
  90007. /**
  90008. * Setup the ground to receive the mirror texture.
  90009. */
  90010. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90011. if (this._groundMaterial) {
  90012. this._groundMaterial.reflectionTexture = this._groundMirror;
  90013. this._groundMaterial.reflectionFresnel = true;
  90014. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90015. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90016. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90017. }
  90018. };
  90019. /**
  90020. * Setup the skybox according to the specified options.
  90021. */
  90022. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90023. var _this = this;
  90024. if (!this._skybox) {
  90025. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90026. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90027. }
  90028. this._skybox.parent = this._rootMesh;
  90029. };
  90030. /**
  90031. * Setup the skybox material according to the specified options.
  90032. */
  90033. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90034. if (!this._skybox) {
  90035. return;
  90036. }
  90037. if (!this._skyboxMaterial) {
  90038. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90039. }
  90040. this._skyboxMaterial.useRGBColor = false;
  90041. this._skyboxMaterial.primaryLevel = 1;
  90042. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90043. this._skyboxMaterial.secondaryLevel = 0;
  90044. this._skyboxMaterial.tertiaryLevel = 0;
  90045. this._skyboxMaterial.enableNoise = true;
  90046. this._skybox.material = this._skyboxMaterial;
  90047. };
  90048. /**
  90049. * Setup the skybox reflection texture according to the specified options.
  90050. */
  90051. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90052. if (!this._skyboxMaterial) {
  90053. return;
  90054. }
  90055. if (this._skyboxTexture) {
  90056. return;
  90057. }
  90058. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90059. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90060. return;
  90061. }
  90062. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90063. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90064. this._skyboxTexture.gammaSpace = false;
  90065. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90066. };
  90067. /**
  90068. * Dispose all the elements created by the Helper.
  90069. */
  90070. EnvironmentHelper.prototype.dispose = function () {
  90071. if (this._groundMaterial) {
  90072. this._groundMaterial.dispose(true, true);
  90073. }
  90074. if (this._skyboxMaterial) {
  90075. this._skyboxMaterial.dispose(true, true);
  90076. }
  90077. this._rootMesh.dispose(false);
  90078. };
  90079. /**
  90080. * Default ground texture URL.
  90081. */
  90082. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90083. /**
  90084. * Default skybox texture URL.
  90085. */
  90086. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90087. /**
  90088. * Default environment texture URL.
  90089. */
  90090. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90091. return EnvironmentHelper;
  90092. }());
  90093. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90094. })(BABYLON || (BABYLON = {}));
  90095. //# sourceMappingURL=babylon.environmentHelper.js.map
  90096. 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}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\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}","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","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","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\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}","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"};
  90097. 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}","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};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\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};"};
  90098. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90099. var BABYLON;
  90100. (function (BABYLON) {
  90101. var GridMaterialDefines = /** @class */ (function (_super) {
  90102. __extends(GridMaterialDefines, _super);
  90103. function GridMaterialDefines() {
  90104. var _this = _super.call(this) || this;
  90105. _this.TRANSPARENT = false;
  90106. _this.FOG = false;
  90107. _this.PREMULTIPLYALPHA = false;
  90108. _this.rebuild();
  90109. return _this;
  90110. }
  90111. return GridMaterialDefines;
  90112. }(BABYLON.MaterialDefines));
  90113. /**
  90114. * The grid materials allows you to wrap any shape with a grid.
  90115. * Colors are customizable.
  90116. */
  90117. var GridMaterial = /** @class */ (function (_super) {
  90118. __extends(GridMaterial, _super);
  90119. /**
  90120. * constructor
  90121. * @param name The name given to the material in order to identify it afterwards.
  90122. * @param scene The scene the material is used in.
  90123. */
  90124. function GridMaterial(name, scene) {
  90125. var _this = _super.call(this, name, scene) || this;
  90126. /**
  90127. * Main color of the grid (e.g. between lines)
  90128. */
  90129. _this.mainColor = BABYLON.Color3.Black();
  90130. /**
  90131. * Color of the grid lines.
  90132. */
  90133. _this.lineColor = BABYLON.Color3.Teal();
  90134. /**
  90135. * The scale of the grid compared to unit.
  90136. */
  90137. _this.gridRatio = 1.0;
  90138. /**
  90139. * Allows setting an offset for the grid lines.
  90140. */
  90141. _this.gridOffset = BABYLON.Vector3.Zero();
  90142. /**
  90143. * The frequency of thicker lines.
  90144. */
  90145. _this.majorUnitFrequency = 10;
  90146. /**
  90147. * The visibility of minor units in the grid.
  90148. */
  90149. _this.minorUnitVisibility = 0.33;
  90150. /**
  90151. * The grid opacity outside of the lines.
  90152. */
  90153. _this.opacity = 1.0;
  90154. /**
  90155. * Determine RBG output is premultiplied by alpha value.
  90156. */
  90157. _this.preMultiplyAlpha = false;
  90158. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  90159. return _this;
  90160. }
  90161. /**
  90162. * Returns wehter or not the grid requires alpha blending.
  90163. */
  90164. GridMaterial.prototype.needAlphaBlending = function () {
  90165. return this.opacity < 1.0;
  90166. };
  90167. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  90168. return this.needAlphaBlending();
  90169. };
  90170. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90171. if (this.isFrozen) {
  90172. if (this._wasPreviouslyReady && subMesh.effect) {
  90173. return true;
  90174. }
  90175. }
  90176. if (!subMesh._materialDefines) {
  90177. subMesh._materialDefines = new GridMaterialDefines();
  90178. }
  90179. var defines = subMesh._materialDefines;
  90180. var scene = this.getScene();
  90181. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90182. if (this._renderId === scene.getRenderId()) {
  90183. return true;
  90184. }
  90185. }
  90186. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  90187. defines.TRANSPARENT = !defines.TRANSPARENT;
  90188. defines.markAsUnprocessed();
  90189. }
  90190. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  90191. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  90192. defines.markAsUnprocessed();
  90193. }
  90194. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  90195. // Get correct effect
  90196. if (defines.isDirty) {
  90197. defines.markAsProcessed();
  90198. scene.resetCachedMaterial();
  90199. // Attributes
  90200. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90201. // Defines
  90202. var join = defines.toString();
  90203. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  90204. }
  90205. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90206. return false;
  90207. }
  90208. this._renderId = scene.getRenderId();
  90209. this._wasPreviouslyReady = true;
  90210. return true;
  90211. };
  90212. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90213. var scene = this.getScene();
  90214. var defines = subMesh._materialDefines;
  90215. if (!defines) {
  90216. return;
  90217. }
  90218. var effect = subMesh.effect;
  90219. if (!effect) {
  90220. return;
  90221. }
  90222. this._activeEffect = effect;
  90223. // Matrices
  90224. this.bindOnlyWorldMatrix(world);
  90225. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  90226. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  90227. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  90228. // Uniforms
  90229. if (this._mustRebind(scene, effect)) {
  90230. this._activeEffect.setColor3("mainColor", this.mainColor);
  90231. this._activeEffect.setColor3("lineColor", this.lineColor);
  90232. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  90233. this._gridControl.x = this.gridRatio;
  90234. this._gridControl.y = Math.round(this.majorUnitFrequency);
  90235. this._gridControl.z = this.minorUnitVisibility;
  90236. this._gridControl.w = this.opacity;
  90237. this._activeEffect.setVector4("gridControl", this._gridControl);
  90238. }
  90239. // Fog
  90240. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90241. this._afterBind(mesh, this._activeEffect);
  90242. };
  90243. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  90244. _super.prototype.dispose.call(this, forceDisposeEffect);
  90245. };
  90246. GridMaterial.prototype.clone = function (name) {
  90247. var _this = this;
  90248. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  90249. };
  90250. GridMaterial.prototype.serialize = function () {
  90251. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90252. serializationObject.customType = "BABYLON.GridMaterial";
  90253. return serializationObject;
  90254. };
  90255. GridMaterial.prototype.getClassName = function () {
  90256. return "GridMaterial";
  90257. };
  90258. GridMaterial.Parse = function (source, scene, rootUrl) {
  90259. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  90260. };
  90261. __decorate([
  90262. BABYLON.serializeAsColor3()
  90263. ], GridMaterial.prototype, "mainColor", void 0);
  90264. __decorate([
  90265. BABYLON.serializeAsColor3()
  90266. ], GridMaterial.prototype, "lineColor", void 0);
  90267. __decorate([
  90268. BABYLON.serialize()
  90269. ], GridMaterial.prototype, "gridRatio", void 0);
  90270. __decorate([
  90271. BABYLON.serializeAsColor3()
  90272. ], GridMaterial.prototype, "gridOffset", void 0);
  90273. __decorate([
  90274. BABYLON.serialize()
  90275. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  90276. __decorate([
  90277. BABYLON.serialize()
  90278. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  90279. __decorate([
  90280. BABYLON.serialize()
  90281. ], GridMaterial.prototype, "opacity", void 0);
  90282. __decorate([
  90283. BABYLON.serialize()
  90284. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  90285. return GridMaterial;
  90286. }(BABYLON.PushMaterial));
  90287. BABYLON.GridMaterial = GridMaterial;
  90288. })(BABYLON || (BABYLON = {}));
  90289. //# sourceMappingURL=babylon.gridmaterial.js.map
  90290. 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}";
  90291. 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}";
  90292. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90293. var BABYLON;
  90294. (function (BABYLON) {
  90295. var GLTFLoaderCoordinateSystemMode;
  90296. (function (GLTFLoaderCoordinateSystemMode) {
  90297. /**
  90298. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  90299. */
  90300. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  90301. /**
  90302. * Sets the useRightHandedSystem flag on the scene.
  90303. */
  90304. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  90305. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  90306. var GLTFLoaderAnimationStartMode;
  90307. (function (GLTFLoaderAnimationStartMode) {
  90308. /**
  90309. * No animation will start.
  90310. */
  90311. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  90312. /**
  90313. * The first animation will start.
  90314. */
  90315. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  90316. /**
  90317. * All animations will start.
  90318. */
  90319. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  90320. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  90321. var GLTFLoaderState;
  90322. (function (GLTFLoaderState) {
  90323. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  90324. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  90325. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  90326. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  90327. var GLTFFileLoader = /** @class */ (function () {
  90328. function GLTFFileLoader() {
  90329. // #region Common options
  90330. /**
  90331. * Raised when the asset has been parsed.
  90332. * The data.json property stores the glTF JSON.
  90333. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  90334. */
  90335. this.onParsedObservable = new BABYLON.Observable();
  90336. // #endregion
  90337. // #region V2 options
  90338. /**
  90339. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  90340. */
  90341. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  90342. /**
  90343. * The animation start mode (NONE, FIRST, ALL).
  90344. */
  90345. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  90346. /**
  90347. * Set to true to compile materials before raising the success callback.
  90348. */
  90349. this.compileMaterials = false;
  90350. /**
  90351. * Set to true to also compile materials with clip planes.
  90352. */
  90353. this.useClipPlane = false;
  90354. /**
  90355. * Set to true to compile shadow generators before raising the success callback.
  90356. */
  90357. this.compileShadowGenerators = false;
  90358. /**
  90359. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  90360. */
  90361. this.onMeshLoadedObservable = new BABYLON.Observable();
  90362. /**
  90363. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  90364. */
  90365. this.onTextureLoadedObservable = new BABYLON.Observable();
  90366. /**
  90367. * Raised when the loader creates a material after parsing the glTF properties of the material.
  90368. */
  90369. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90370. /**
  90371. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  90372. */
  90373. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  90374. /**
  90375. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  90376. * For assets with LODs, raised when all of the LODs are complete.
  90377. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  90378. */
  90379. this.onCompleteObservable = new BABYLON.Observable();
  90380. /**
  90381. * Raised when the loader is disposed.
  90382. */
  90383. this.onDisposeObservable = new BABYLON.Observable();
  90384. /**
  90385. * Raised after a loader extension is created.
  90386. * Set additional options for a loader extension in this event.
  90387. */
  90388. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90389. // #endregion
  90390. this._loader = null;
  90391. this.name = "gltf";
  90392. this.extensions = {
  90393. ".gltf": { isBinary: false },
  90394. ".glb": { isBinary: true }
  90395. };
  90396. }
  90397. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  90398. set: function (callback) {
  90399. if (this._onParsedObserver) {
  90400. this.onParsedObservable.remove(this._onParsedObserver);
  90401. }
  90402. this._onParsedObserver = this.onParsedObservable.add(callback);
  90403. },
  90404. enumerable: true,
  90405. configurable: true
  90406. });
  90407. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  90408. set: function (callback) {
  90409. if (this._onMeshLoadedObserver) {
  90410. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  90411. }
  90412. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  90413. },
  90414. enumerable: true,
  90415. configurable: true
  90416. });
  90417. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  90418. set: function (callback) {
  90419. if (this._onTextureLoadedObserver) {
  90420. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  90421. }
  90422. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  90423. },
  90424. enumerable: true,
  90425. configurable: true
  90426. });
  90427. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  90428. set: function (callback) {
  90429. if (this._onMaterialLoadedObserver) {
  90430. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  90431. }
  90432. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  90433. },
  90434. enumerable: true,
  90435. configurable: true
  90436. });
  90437. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  90438. set: function (callback) {
  90439. if (this._onAnimationGroupLoadedObserver) {
  90440. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  90441. }
  90442. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  90443. },
  90444. enumerable: true,
  90445. configurable: true
  90446. });
  90447. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  90448. set: function (callback) {
  90449. if (this._onCompleteObserver) {
  90450. this.onCompleteObservable.remove(this._onCompleteObserver);
  90451. }
  90452. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  90453. },
  90454. enumerable: true,
  90455. configurable: true
  90456. });
  90457. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  90458. set: function (callback) {
  90459. if (this._onDisposeObserver) {
  90460. this.onDisposeObservable.remove(this._onDisposeObserver);
  90461. }
  90462. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  90463. },
  90464. enumerable: true,
  90465. configurable: true
  90466. });
  90467. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  90468. set: function (callback) {
  90469. if (this._onExtensionLoadedObserver) {
  90470. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  90471. }
  90472. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  90473. },
  90474. enumerable: true,
  90475. configurable: true
  90476. });
  90477. /**
  90478. * Gets a promise that resolves when the asset is completely loaded.
  90479. * @returns A promise that resolves when the asset is completely loaded.
  90480. */
  90481. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  90482. var _this = this;
  90483. return new Promise(function (resolve) {
  90484. _this.onCompleteObservable.add(function () {
  90485. resolve();
  90486. }, undefined, undefined, undefined, true);
  90487. });
  90488. };
  90489. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  90490. /**
  90491. * The loader state or null if not active.
  90492. */
  90493. get: function () {
  90494. return this._loader ? this._loader.state : null;
  90495. },
  90496. enumerable: true,
  90497. configurable: true
  90498. });
  90499. /**
  90500. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  90501. */
  90502. GLTFFileLoader.prototype.dispose = function () {
  90503. if (this._loader) {
  90504. this._loader.dispose();
  90505. this._loader = null;
  90506. }
  90507. this.onMeshLoadedObservable.clear();
  90508. this.onTextureLoadedObservable.clear();
  90509. this.onMaterialLoadedObservable.clear();
  90510. this.onDisposeObservable.notifyObservers(this);
  90511. this.onDisposeObservable.clear();
  90512. };
  90513. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90514. var _this = this;
  90515. return Promise.resolve().then(function () {
  90516. var loaderData = _this._parse(data);
  90517. _this._loader = _this._getLoader(loaderData);
  90518. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  90519. });
  90520. };
  90521. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90522. var _this = this;
  90523. return Promise.resolve().then(function () {
  90524. var loaderData = _this._parse(data);
  90525. _this._loader = _this._getLoader(loaderData);
  90526. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  90527. });
  90528. };
  90529. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  90530. var _this = this;
  90531. return Promise.resolve().then(function () {
  90532. var loaderData = _this._parse(data);
  90533. _this._loader = _this._getLoader(loaderData);
  90534. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  90535. var container = new BABYLON.AssetContainer(scene);
  90536. Array.prototype.push.apply(container.meshes, result.meshes);
  90537. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  90538. Array.prototype.push.apply(container.skeletons, result.skeletons);
  90539. container.removeAllFromScene();
  90540. return container;
  90541. });
  90542. });
  90543. };
  90544. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  90545. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  90546. };
  90547. GLTFFileLoader.prototype.createPlugin = function () {
  90548. return new GLTFFileLoader();
  90549. };
  90550. GLTFFileLoader.prototype._parse = function (data) {
  90551. var parsedData;
  90552. if (data instanceof ArrayBuffer) {
  90553. parsedData = GLTFFileLoader._parseBinary(data);
  90554. }
  90555. else {
  90556. parsedData = {
  90557. json: JSON.parse(data),
  90558. bin: null
  90559. };
  90560. }
  90561. this.onParsedObservable.notifyObservers(parsedData);
  90562. this.onParsedObservable.clear();
  90563. return parsedData;
  90564. };
  90565. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  90566. var _this = this;
  90567. var loaderVersion = { major: 2, minor: 0 };
  90568. var asset = loaderData.json.asset || {};
  90569. var version = GLTFFileLoader._parseVersion(asset.version);
  90570. if (!version) {
  90571. throw new Error("Invalid version: " + asset.version);
  90572. }
  90573. if (asset.minVersion !== undefined) {
  90574. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  90575. if (!minVersion) {
  90576. throw new Error("Invalid minimum version: " + asset.minVersion);
  90577. }
  90578. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  90579. throw new Error("Incompatible minimum version: " + asset.minVersion);
  90580. }
  90581. }
  90582. var createLoaders = {
  90583. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  90584. 2: GLTFFileLoader.CreateGLTFLoaderV2
  90585. };
  90586. var createLoader = createLoaders[version.major];
  90587. if (!createLoader) {
  90588. throw new Error("Unsupported version: " + asset.version);
  90589. }
  90590. var loader = createLoader();
  90591. loader.coordinateSystemMode = this.coordinateSystemMode;
  90592. loader.animationStartMode = this.animationStartMode;
  90593. loader.compileMaterials = this.compileMaterials;
  90594. loader.useClipPlane = this.useClipPlane;
  90595. loader.compileShadowGenerators = this.compileShadowGenerators;
  90596. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90597. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90598. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90599. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90600. loader.onCompleteObservable.add(function () {
  90601. _this.onMeshLoadedObservable.clear();
  90602. _this.onTextureLoadedObservable.clear();
  90603. _this.onMaterialLoadedObservable.clear();
  90604. _this.onCompleteObservable.notifyObservers(_this);
  90605. _this.onCompleteObservable.clear();
  90606. });
  90607. return loader;
  90608. };
  90609. GLTFFileLoader._parseBinary = function (data) {
  90610. var Binary = {
  90611. Magic: 0x46546C67
  90612. };
  90613. var binaryReader = new BinaryReader(data);
  90614. var magic = binaryReader.readUint32();
  90615. if (magic !== Binary.Magic) {
  90616. throw new Error("Unexpected magic: " + magic);
  90617. }
  90618. var version = binaryReader.readUint32();
  90619. switch (version) {
  90620. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90621. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90622. }
  90623. throw new Error("Unsupported version: " + version);
  90624. };
  90625. GLTFFileLoader._parseV1 = function (binaryReader) {
  90626. var ContentFormat = {
  90627. JSON: 0
  90628. };
  90629. var length = binaryReader.readUint32();
  90630. if (length != binaryReader.getLength()) {
  90631. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90632. }
  90633. var contentLength = binaryReader.readUint32();
  90634. var contentFormat = binaryReader.readUint32();
  90635. var content;
  90636. switch (contentFormat) {
  90637. case ContentFormat.JSON: {
  90638. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90639. break;
  90640. }
  90641. default: {
  90642. throw new Error("Unexpected content format: " + contentFormat);
  90643. }
  90644. }
  90645. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90646. var body = binaryReader.readUint8Array(bytesRemaining);
  90647. return {
  90648. json: content,
  90649. bin: body
  90650. };
  90651. };
  90652. GLTFFileLoader._parseV2 = function (binaryReader) {
  90653. var ChunkFormat = {
  90654. JSON: 0x4E4F534A,
  90655. BIN: 0x004E4942
  90656. };
  90657. var length = binaryReader.readUint32();
  90658. if (length !== binaryReader.getLength()) {
  90659. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90660. }
  90661. // JSON chunk
  90662. var chunkLength = binaryReader.readUint32();
  90663. var chunkFormat = binaryReader.readUint32();
  90664. if (chunkFormat !== ChunkFormat.JSON) {
  90665. throw new Error("First chunk format is not JSON");
  90666. }
  90667. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90668. // Look for BIN chunk
  90669. var bin = null;
  90670. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90671. var chunkLength_1 = binaryReader.readUint32();
  90672. var chunkFormat_1 = binaryReader.readUint32();
  90673. switch (chunkFormat_1) {
  90674. case ChunkFormat.JSON: {
  90675. throw new Error("Unexpected JSON chunk");
  90676. }
  90677. case ChunkFormat.BIN: {
  90678. bin = binaryReader.readUint8Array(chunkLength_1);
  90679. break;
  90680. }
  90681. default: {
  90682. // ignore unrecognized chunkFormat
  90683. binaryReader.skipBytes(chunkLength_1);
  90684. break;
  90685. }
  90686. }
  90687. }
  90688. return {
  90689. json: json,
  90690. bin: bin
  90691. };
  90692. };
  90693. GLTFFileLoader._parseVersion = function (version) {
  90694. if (version === "1.0" || version === "1.0.1") {
  90695. return {
  90696. major: 1,
  90697. minor: 0
  90698. };
  90699. }
  90700. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90701. if (!match) {
  90702. return null;
  90703. }
  90704. return {
  90705. major: parseInt(match[1]),
  90706. minor: parseInt(match[2])
  90707. };
  90708. };
  90709. GLTFFileLoader._compareVersion = function (a, b) {
  90710. if (a.major > b.major)
  90711. return 1;
  90712. if (a.major < b.major)
  90713. return -1;
  90714. if (a.minor > b.minor)
  90715. return 1;
  90716. if (a.minor < b.minor)
  90717. return -1;
  90718. return 0;
  90719. };
  90720. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90721. var result = "";
  90722. var length = buffer.byteLength;
  90723. for (var i = 0; i < length; i++) {
  90724. result += String.fromCharCode(buffer[i]);
  90725. }
  90726. return result;
  90727. };
  90728. // #endregion
  90729. // #region V1 options
  90730. GLTFFileLoader.IncrementalLoading = true;
  90731. GLTFFileLoader.HomogeneousCoordinates = false;
  90732. return GLTFFileLoader;
  90733. }());
  90734. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90735. var BinaryReader = /** @class */ (function () {
  90736. function BinaryReader(arrayBuffer) {
  90737. this._arrayBuffer = arrayBuffer;
  90738. this._dataView = new DataView(arrayBuffer);
  90739. this._byteOffset = 0;
  90740. }
  90741. BinaryReader.prototype.getPosition = function () {
  90742. return this._byteOffset;
  90743. };
  90744. BinaryReader.prototype.getLength = function () {
  90745. return this._arrayBuffer.byteLength;
  90746. };
  90747. BinaryReader.prototype.readUint32 = function () {
  90748. var value = this._dataView.getUint32(this._byteOffset, true);
  90749. this._byteOffset += 4;
  90750. return value;
  90751. };
  90752. BinaryReader.prototype.readUint8Array = function (length) {
  90753. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90754. this._byteOffset += length;
  90755. return value;
  90756. };
  90757. BinaryReader.prototype.skipBytes = function (length) {
  90758. this._byteOffset += length;
  90759. };
  90760. return BinaryReader;
  90761. }());
  90762. if (BABYLON.SceneLoader) {
  90763. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90764. }
  90765. })(BABYLON || (BABYLON = {}));
  90766. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90767. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90768. var BABYLON;
  90769. (function (BABYLON) {
  90770. var GLTF1;
  90771. (function (GLTF1) {
  90772. /**
  90773. * Enums
  90774. */
  90775. var EComponentType;
  90776. (function (EComponentType) {
  90777. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90778. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90779. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90780. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90781. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90782. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90783. var EShaderType;
  90784. (function (EShaderType) {
  90785. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90786. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90787. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90788. var EParameterType;
  90789. (function (EParameterType) {
  90790. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90791. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90792. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90793. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90794. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90795. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90796. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90797. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90798. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90799. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90800. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90801. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90802. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90803. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90804. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90805. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90806. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90807. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90808. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90809. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90810. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90811. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90812. var ETextureWrapMode;
  90813. (function (ETextureWrapMode) {
  90814. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90815. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90816. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90817. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90818. var ETextureFilterType;
  90819. (function (ETextureFilterType) {
  90820. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90821. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90822. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90823. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90824. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90825. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90826. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90827. var ETextureFormat;
  90828. (function (ETextureFormat) {
  90829. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90830. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90831. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90832. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90833. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90834. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90835. var ECullingType;
  90836. (function (ECullingType) {
  90837. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90838. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90839. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90840. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90841. var EBlendingFunction;
  90842. (function (EBlendingFunction) {
  90843. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90844. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90845. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90846. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90847. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90848. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90849. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90850. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90851. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90852. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90853. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90854. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90855. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90856. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90857. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90858. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90859. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90860. })(BABYLON || (BABYLON = {}));
  90861. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90862. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90863. var BABYLON;
  90864. (function (BABYLON) {
  90865. var GLTF1;
  90866. (function (GLTF1) {
  90867. /**
  90868. * Tokenizer. Used for shaders compatibility
  90869. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90870. */
  90871. var ETokenType;
  90872. (function (ETokenType) {
  90873. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90874. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90875. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90876. })(ETokenType || (ETokenType = {}));
  90877. var Tokenizer = /** @class */ (function () {
  90878. function Tokenizer(toParse) {
  90879. this._pos = 0;
  90880. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90881. this._toParse = toParse;
  90882. this._maxPos = toParse.length;
  90883. }
  90884. Tokenizer.prototype.getNextToken = function () {
  90885. if (this.isEnd())
  90886. return ETokenType.END_OF_INPUT;
  90887. this.currentString = this.read();
  90888. this.currentToken = ETokenType.UNKNOWN;
  90889. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90890. this.currentToken = ETokenType.IDENTIFIER;
  90891. this.currentIdentifier = this.currentString;
  90892. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90893. this.currentIdentifier += this.currentString;
  90894. this.forward();
  90895. }
  90896. }
  90897. return this.currentToken;
  90898. };
  90899. Tokenizer.prototype.peek = function () {
  90900. return this._toParse[this._pos];
  90901. };
  90902. Tokenizer.prototype.read = function () {
  90903. return this._toParse[this._pos++];
  90904. };
  90905. Tokenizer.prototype.forward = function () {
  90906. this._pos++;
  90907. };
  90908. Tokenizer.prototype.isEnd = function () {
  90909. return this._pos >= this._maxPos;
  90910. };
  90911. return Tokenizer;
  90912. }());
  90913. /**
  90914. * Values
  90915. */
  90916. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90917. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90918. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90919. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90920. /**
  90921. * Parse
  90922. */
  90923. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90924. for (var buf in parsedBuffers) {
  90925. var parsedBuffer = parsedBuffers[buf];
  90926. gltfRuntime.buffers[buf] = parsedBuffer;
  90927. gltfRuntime.buffersCount++;
  90928. }
  90929. };
  90930. var parseShaders = function (parsedShaders, gltfRuntime) {
  90931. for (var sha in parsedShaders) {
  90932. var parsedShader = parsedShaders[sha];
  90933. gltfRuntime.shaders[sha] = parsedShader;
  90934. gltfRuntime.shaderscount++;
  90935. }
  90936. };
  90937. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90938. for (var object in parsedObjects) {
  90939. var parsedObject = parsedObjects[object];
  90940. gltfRuntime[runtimeProperty][object] = parsedObject;
  90941. }
  90942. };
  90943. /**
  90944. * Utils
  90945. */
  90946. var normalizeUVs = function (buffer) {
  90947. if (!buffer) {
  90948. return;
  90949. }
  90950. for (var i = 0; i < buffer.length / 2; i++) {
  90951. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90952. }
  90953. };
  90954. var getAttribute = function (attributeParameter) {
  90955. if (attributeParameter.semantic === "NORMAL") {
  90956. return "normal";
  90957. }
  90958. else if (attributeParameter.semantic === "POSITION") {
  90959. return "position";
  90960. }
  90961. else if (attributeParameter.semantic === "JOINT") {
  90962. return "matricesIndices";
  90963. }
  90964. else if (attributeParameter.semantic === "WEIGHT") {
  90965. return "matricesWeights";
  90966. }
  90967. else if (attributeParameter.semantic === "COLOR") {
  90968. return "color";
  90969. }
  90970. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90971. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90972. return "uv" + (channel === 0 ? "" : channel + 1);
  90973. }
  90974. return null;
  90975. };
  90976. /**
  90977. * Loads and creates animations
  90978. */
  90979. var loadAnimations = function (gltfRuntime) {
  90980. for (var anim in gltfRuntime.animations) {
  90981. var animation = gltfRuntime.animations[anim];
  90982. if (!animation.channels || !animation.samplers) {
  90983. continue;
  90984. }
  90985. var lastAnimation = null;
  90986. for (var i = 0; i < animation.channels.length; i++) {
  90987. // Get parameters and load buffers
  90988. var channel = animation.channels[i];
  90989. var sampler = animation.samplers[channel.sampler];
  90990. if (!sampler) {
  90991. continue;
  90992. }
  90993. var inputData = null;
  90994. var outputData = null;
  90995. if (animation.parameters) {
  90996. inputData = animation.parameters[sampler.input];
  90997. outputData = animation.parameters[sampler.output];
  90998. }
  90999. else {
  91000. inputData = sampler.input;
  91001. outputData = sampler.output;
  91002. }
  91003. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  91004. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  91005. var targetID = channel.target.id;
  91006. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  91007. if (targetNode === null) {
  91008. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  91009. }
  91010. if (targetNode === null) {
  91011. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  91012. continue;
  91013. }
  91014. var isBone = targetNode instanceof BABYLON.Bone;
  91015. // Get target path (position, rotation or scaling)
  91016. var targetPath = channel.target.path;
  91017. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  91018. if (targetPathIndex !== -1) {
  91019. targetPath = babylonAnimationPaths[targetPathIndex];
  91020. }
  91021. // Determine animation type
  91022. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  91023. if (!isBone) {
  91024. if (targetPath === "rotationQuaternion") {
  91025. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91026. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  91027. }
  91028. else {
  91029. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91030. }
  91031. }
  91032. // Create animation and key frames
  91033. var babylonAnimation = null;
  91034. var keys = [];
  91035. var arrayOffset = 0;
  91036. var modifyKey = false;
  91037. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  91038. babylonAnimation = lastAnimation;
  91039. modifyKey = true;
  91040. }
  91041. if (!modifyKey) {
  91042. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91043. }
  91044. // For each frame
  91045. for (var j = 0; j < bufferInput.length; j++) {
  91046. var value = null;
  91047. if (targetPath === "rotationQuaternion") {
  91048. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  91049. arrayOffset += 4;
  91050. }
  91051. else {
  91052. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  91053. arrayOffset += 3;
  91054. }
  91055. if (isBone) {
  91056. var bone = targetNode;
  91057. var translation = BABYLON.Vector3.Zero();
  91058. var rotationQuaternion = new BABYLON.Quaternion();
  91059. var scaling = BABYLON.Vector3.Zero();
  91060. // Warning on decompose
  91061. var mat = bone.getBaseMatrix();
  91062. if (modifyKey && lastAnimation) {
  91063. mat = lastAnimation.getKeys()[j].value;
  91064. }
  91065. mat.decompose(scaling, rotationQuaternion, translation);
  91066. if (targetPath === "position") {
  91067. translation = value;
  91068. }
  91069. else if (targetPath === "rotationQuaternion") {
  91070. rotationQuaternion = value;
  91071. }
  91072. else {
  91073. scaling = value;
  91074. }
  91075. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  91076. }
  91077. if (!modifyKey) {
  91078. keys.push({
  91079. frame: bufferInput[j],
  91080. value: value
  91081. });
  91082. }
  91083. else if (lastAnimation) {
  91084. lastAnimation.getKeys()[j].value = value;
  91085. }
  91086. }
  91087. // Finish
  91088. if (!modifyKey && babylonAnimation) {
  91089. babylonAnimation.setKeys(keys);
  91090. targetNode.animations.push(babylonAnimation);
  91091. }
  91092. lastAnimation = babylonAnimation;
  91093. gltfRuntime.scene.stopAnimation(targetNode);
  91094. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  91095. }
  91096. }
  91097. };
  91098. /**
  91099. * Returns the bones transformation matrix
  91100. */
  91101. var configureBoneTransformation = function (node) {
  91102. var mat = null;
  91103. if (node.translation || node.rotation || node.scale) {
  91104. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  91105. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  91106. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  91107. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  91108. }
  91109. else {
  91110. mat = BABYLON.Matrix.FromArray(node.matrix);
  91111. }
  91112. return mat;
  91113. };
  91114. /**
  91115. * Returns the parent bone
  91116. */
  91117. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  91118. // Try to find
  91119. for (var i = 0; i < newSkeleton.bones.length; i++) {
  91120. if (newSkeleton.bones[i].name === jointName) {
  91121. return newSkeleton.bones[i];
  91122. }
  91123. }
  91124. // Not found, search in gltf nodes
  91125. var nodes = gltfRuntime.nodes;
  91126. for (var nde in nodes) {
  91127. var node = nodes[nde];
  91128. if (!node.jointName) {
  91129. continue;
  91130. }
  91131. var children = node.children;
  91132. for (var i = 0; i < children.length; i++) {
  91133. var child = gltfRuntime.nodes[children[i]];
  91134. if (!child.jointName) {
  91135. continue;
  91136. }
  91137. if (child.jointName === jointName) {
  91138. var mat = configureBoneTransformation(node);
  91139. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  91140. bone.id = nde;
  91141. return bone;
  91142. }
  91143. }
  91144. }
  91145. return null;
  91146. };
  91147. /**
  91148. * Returns the appropriate root node
  91149. */
  91150. var getNodeToRoot = function (nodesToRoot, id) {
  91151. for (var i = 0; i < nodesToRoot.length; i++) {
  91152. var nodeToRoot = nodesToRoot[i];
  91153. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  91154. var child = nodeToRoot.node.children[j];
  91155. if (child === id) {
  91156. return nodeToRoot.bone;
  91157. }
  91158. }
  91159. }
  91160. return null;
  91161. };
  91162. /**
  91163. * Returns the node with the joint name
  91164. */
  91165. var getJointNode = function (gltfRuntime, jointName) {
  91166. var nodes = gltfRuntime.nodes;
  91167. var node = nodes[jointName];
  91168. if (node) {
  91169. return {
  91170. node: node,
  91171. id: jointName
  91172. };
  91173. }
  91174. for (var nde in nodes) {
  91175. node = nodes[nde];
  91176. if (node.jointName === jointName) {
  91177. return {
  91178. node: node,
  91179. id: nde
  91180. };
  91181. }
  91182. }
  91183. return null;
  91184. };
  91185. /**
  91186. * Checks if a nodes is in joints
  91187. */
  91188. var nodeIsInJoints = function (skins, id) {
  91189. for (var i = 0; i < skins.jointNames.length; i++) {
  91190. if (skins.jointNames[i] === id) {
  91191. return true;
  91192. }
  91193. }
  91194. return false;
  91195. };
  91196. /**
  91197. * Fills the nodes to root for bones and builds hierarchy
  91198. */
  91199. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  91200. // Creates nodes for root
  91201. for (var nde in gltfRuntime.nodes) {
  91202. var node = gltfRuntime.nodes[nde];
  91203. var id = nde;
  91204. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  91205. continue;
  91206. }
  91207. // Create node to root bone
  91208. var mat = configureBoneTransformation(node);
  91209. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  91210. bone.id = id;
  91211. nodesToRoot.push({ bone: bone, node: node, id: id });
  91212. }
  91213. // Parenting
  91214. for (var i = 0; i < nodesToRoot.length; i++) {
  91215. var nodeToRoot = nodesToRoot[i];
  91216. var children = nodeToRoot.node.children;
  91217. for (var j = 0; j < children.length; j++) {
  91218. var child = null;
  91219. for (var k = 0; k < nodesToRoot.length; k++) {
  91220. if (nodesToRoot[k].id === children[j]) {
  91221. child = nodesToRoot[k];
  91222. break;
  91223. }
  91224. }
  91225. if (child) {
  91226. child.bone._parent = nodeToRoot.bone;
  91227. nodeToRoot.bone.children.push(child.bone);
  91228. }
  91229. }
  91230. }
  91231. };
  91232. /**
  91233. * Imports a skeleton
  91234. */
  91235. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  91236. if (!newSkeleton) {
  91237. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  91238. }
  91239. if (!skins.babylonSkeleton) {
  91240. return newSkeleton;
  91241. }
  91242. // Find the root bones
  91243. var nodesToRoot = [];
  91244. var nodesToRootToAdd = [];
  91245. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  91246. newSkeleton.bones = [];
  91247. // Joints
  91248. for (var i = 0; i < skins.jointNames.length; i++) {
  91249. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91250. if (!jointNode) {
  91251. continue;
  91252. }
  91253. var node = jointNode.node;
  91254. if (!node) {
  91255. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  91256. continue;
  91257. }
  91258. var id = jointNode.id;
  91259. // Optimize, if the bone already exists...
  91260. var existingBone = gltfRuntime.scene.getBoneByID(id);
  91261. if (existingBone) {
  91262. newSkeleton.bones.push(existingBone);
  91263. continue;
  91264. }
  91265. // Search for parent bone
  91266. var foundBone = false;
  91267. var parentBone = null;
  91268. for (var j = 0; j < i; j++) {
  91269. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  91270. if (!jointNode_1) {
  91271. continue;
  91272. }
  91273. var joint = jointNode_1.node;
  91274. if (!joint) {
  91275. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  91276. continue;
  91277. }
  91278. var children = joint.children;
  91279. if (!children) {
  91280. continue;
  91281. }
  91282. foundBone = false;
  91283. for (var k = 0; k < children.length; k++) {
  91284. if (children[k] === id) {
  91285. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  91286. foundBone = true;
  91287. break;
  91288. }
  91289. }
  91290. if (foundBone) {
  91291. break;
  91292. }
  91293. }
  91294. // Create bone
  91295. var mat = configureBoneTransformation(node);
  91296. if (!parentBone && nodesToRoot.length > 0) {
  91297. parentBone = getNodeToRoot(nodesToRoot, id);
  91298. if (parentBone) {
  91299. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  91300. nodesToRootToAdd.push(parentBone);
  91301. }
  91302. }
  91303. }
  91304. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  91305. bone.id = id;
  91306. }
  91307. // Polish
  91308. var bones = newSkeleton.bones;
  91309. newSkeleton.bones = [];
  91310. for (var i = 0; i < skins.jointNames.length; i++) {
  91311. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91312. if (!jointNode) {
  91313. continue;
  91314. }
  91315. for (var j = 0; j < bones.length; j++) {
  91316. if (bones[j].id === jointNode.id) {
  91317. newSkeleton.bones.push(bones[j]);
  91318. break;
  91319. }
  91320. }
  91321. }
  91322. newSkeleton.prepare();
  91323. // Finish
  91324. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  91325. newSkeleton.bones.push(nodesToRootToAdd[i]);
  91326. }
  91327. return newSkeleton;
  91328. };
  91329. /**
  91330. * Imports a mesh and its geometries
  91331. */
  91332. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  91333. if (!newMesh) {
  91334. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91335. newMesh.id = id;
  91336. }
  91337. if (!node.babylonNode) {
  91338. return newMesh;
  91339. }
  91340. var subMaterials = [];
  91341. var vertexData = null;
  91342. var verticesStarts = new Array();
  91343. var verticesCounts = new Array();
  91344. var indexStarts = new Array();
  91345. var indexCounts = new Array();
  91346. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91347. var meshID = meshes[meshIndex];
  91348. var mesh = gltfRuntime.meshes[meshID];
  91349. if (!mesh) {
  91350. continue;
  91351. }
  91352. // Positions, normals and UVs
  91353. for (var i = 0; i < mesh.primitives.length; i++) {
  91354. // Temporary vertex data
  91355. var tempVertexData = new BABYLON.VertexData();
  91356. var primitive = mesh.primitives[i];
  91357. if (primitive.mode !== 4) {
  91358. // continue;
  91359. }
  91360. var attributes = primitive.attributes;
  91361. var accessor = null;
  91362. var buffer = null;
  91363. // Set positions, normal and uvs
  91364. for (var semantic in attributes) {
  91365. // Link accessor and buffer view
  91366. accessor = gltfRuntime.accessors[attributes[semantic]];
  91367. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91368. if (semantic === "NORMAL") {
  91369. tempVertexData.normals = new Float32Array(buffer.length);
  91370. tempVertexData.normals.set(buffer);
  91371. }
  91372. else if (semantic === "POSITION") {
  91373. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  91374. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  91375. for (var j = 0; j < buffer.length; j += 4) {
  91376. tempVertexData.positions[j] = buffer[j];
  91377. tempVertexData.positions[j + 1] = buffer[j + 1];
  91378. tempVertexData.positions[j + 2] = buffer[j + 2];
  91379. }
  91380. }
  91381. else {
  91382. tempVertexData.positions = new Float32Array(buffer.length);
  91383. tempVertexData.positions.set(buffer);
  91384. }
  91385. verticesCounts.push(tempVertexData.positions.length);
  91386. }
  91387. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  91388. var channel = Number(semantic.split("_")[1]);
  91389. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  91390. var uvs = new Float32Array(buffer.length);
  91391. uvs.set(buffer);
  91392. normalizeUVs(uvs);
  91393. tempVertexData.set(uvs, uvKind);
  91394. }
  91395. else if (semantic === "JOINT") {
  91396. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  91397. tempVertexData.matricesIndices.set(buffer);
  91398. }
  91399. else if (semantic === "WEIGHT") {
  91400. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  91401. tempVertexData.matricesWeights.set(buffer);
  91402. }
  91403. else if (semantic === "COLOR") {
  91404. tempVertexData.colors = new Float32Array(buffer.length);
  91405. tempVertexData.colors.set(buffer);
  91406. }
  91407. }
  91408. // Indices
  91409. accessor = gltfRuntime.accessors[primitive.indices];
  91410. if (accessor) {
  91411. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91412. tempVertexData.indices = new Int32Array(buffer.length);
  91413. tempVertexData.indices.set(buffer);
  91414. indexCounts.push(tempVertexData.indices.length);
  91415. }
  91416. else {
  91417. // Set indices on the fly
  91418. var indices = [];
  91419. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  91420. indices.push(j);
  91421. }
  91422. tempVertexData.indices = new Int32Array(indices);
  91423. indexCounts.push(tempVertexData.indices.length);
  91424. }
  91425. if (!vertexData) {
  91426. vertexData = tempVertexData;
  91427. }
  91428. else {
  91429. vertexData.merge(tempVertexData);
  91430. }
  91431. // Sub material
  91432. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  91433. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  91434. // Update vertices start and index start
  91435. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  91436. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  91437. }
  91438. }
  91439. var material;
  91440. if (subMaterials.length > 1) {
  91441. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  91442. material.subMaterials = subMaterials;
  91443. }
  91444. else {
  91445. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  91446. }
  91447. if (subMaterials.length === 1) {
  91448. material = subMaterials[0];
  91449. }
  91450. if (!newMesh.material) {
  91451. newMesh.material = material;
  91452. }
  91453. // Apply geometry
  91454. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  91455. newMesh.computeWorldMatrix(true);
  91456. // Apply submeshes
  91457. newMesh.subMeshes = [];
  91458. var index = 0;
  91459. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91460. var meshID = meshes[meshIndex];
  91461. var mesh = gltfRuntime.meshes[meshID];
  91462. if (!mesh) {
  91463. continue;
  91464. }
  91465. for (var i = 0; i < mesh.primitives.length; i++) {
  91466. if (mesh.primitives[i].mode !== 4) {
  91467. //continue;
  91468. }
  91469. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  91470. index++;
  91471. }
  91472. }
  91473. // Finish
  91474. return newMesh;
  91475. };
  91476. /**
  91477. * Configure node transformation from position, rotation and scaling
  91478. */
  91479. var configureNode = function (newNode, position, rotation, scaling) {
  91480. if (newNode.position) {
  91481. newNode.position = position;
  91482. }
  91483. if (newNode.rotationQuaternion || newNode.rotation) {
  91484. newNode.rotationQuaternion = rotation;
  91485. }
  91486. if (newNode.scaling) {
  91487. newNode.scaling = scaling;
  91488. }
  91489. };
  91490. /**
  91491. * Configures node from transformation matrix
  91492. */
  91493. var configureNodeFromMatrix = function (newNode, node, parent) {
  91494. if (node.matrix) {
  91495. var position = new BABYLON.Vector3(0, 0, 0);
  91496. var rotation = new BABYLON.Quaternion();
  91497. var scaling = new BABYLON.Vector3(0, 0, 0);
  91498. var mat = BABYLON.Matrix.FromArray(node.matrix);
  91499. mat.decompose(scaling, rotation, position);
  91500. configureNode(newNode, position, rotation, scaling);
  91501. }
  91502. else if (node.translation && node.rotation && node.scale) {
  91503. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  91504. }
  91505. newNode.computeWorldMatrix(true);
  91506. };
  91507. /**
  91508. * Imports a node
  91509. */
  91510. var importNode = function (gltfRuntime, node, id, parent) {
  91511. var lastNode = null;
  91512. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  91513. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  91514. return null;
  91515. }
  91516. }
  91517. // Meshes
  91518. if (node.skin) {
  91519. if (node.meshes) {
  91520. var skin = gltfRuntime.skins[node.skin];
  91521. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  91522. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  91523. if (newMesh.skeleton === null) {
  91524. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  91525. if (!skin.babylonSkeleton) {
  91526. skin.babylonSkeleton = newMesh.skeleton;
  91527. }
  91528. }
  91529. lastNode = newMesh;
  91530. }
  91531. }
  91532. else if (node.meshes) {
  91533. /**
  91534. * Improve meshes property
  91535. */
  91536. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  91537. lastNode = newMesh;
  91538. }
  91539. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91540. var light = gltfRuntime.lights[node.light];
  91541. if (light) {
  91542. if (light.type === "ambient") {
  91543. var ambienLight = light[light.type];
  91544. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91545. hemiLight.name = node.name || "";
  91546. if (ambienLight.color) {
  91547. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  91548. }
  91549. lastNode = hemiLight;
  91550. }
  91551. else if (light.type === "directional") {
  91552. var directionalLight = light[light.type];
  91553. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91554. dirLight.name = node.name || "";
  91555. if (directionalLight.color) {
  91556. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  91557. }
  91558. lastNode = dirLight;
  91559. }
  91560. else if (light.type === "point") {
  91561. var pointLight = light[light.type];
  91562. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91563. ptLight.name = node.name || "";
  91564. if (pointLight.color) {
  91565. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  91566. }
  91567. lastNode = ptLight;
  91568. }
  91569. else if (light.type === "spot") {
  91570. var spotLight = light[light.type];
  91571. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  91572. spLight.name = node.name || "";
  91573. if (spotLight.color) {
  91574. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  91575. }
  91576. if (spotLight.fallOfAngle) {
  91577. spLight.angle = spotLight.fallOfAngle;
  91578. }
  91579. if (spotLight.fallOffExponent) {
  91580. spLight.exponent = spotLight.fallOffExponent;
  91581. }
  91582. lastNode = spLight;
  91583. }
  91584. }
  91585. }
  91586. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91587. var camera = gltfRuntime.cameras[node.camera];
  91588. if (camera) {
  91589. if (camera.type === "orthographic") {
  91590. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91591. orthoCamera.name = node.name || "";
  91592. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  91593. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91594. lastNode = orthoCamera;
  91595. }
  91596. else if (camera.type === "perspective") {
  91597. var perspectiveCamera = camera[camera.type];
  91598. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91599. persCamera.name = node.name || "";
  91600. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91601. if (!perspectiveCamera.aspectRatio) {
  91602. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91603. }
  91604. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91605. persCamera.maxZ = perspectiveCamera.zfar;
  91606. persCamera.minZ = perspectiveCamera.znear;
  91607. }
  91608. lastNode = persCamera;
  91609. }
  91610. }
  91611. }
  91612. // Empty node
  91613. if (!node.jointName) {
  91614. if (node.babylonNode) {
  91615. return node.babylonNode;
  91616. }
  91617. else if (lastNode === null) {
  91618. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91619. node.babylonNode = dummy;
  91620. lastNode = dummy;
  91621. }
  91622. }
  91623. if (lastNode !== null) {
  91624. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91625. configureNodeFromMatrix(lastNode, node, parent);
  91626. }
  91627. else {
  91628. var translation = node.translation || [0, 0, 0];
  91629. var rotation = node.rotation || [0, 0, 0, 1];
  91630. var scale = node.scale || [1, 1, 1];
  91631. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91632. }
  91633. lastNode.updateCache(true);
  91634. node.babylonNode = lastNode;
  91635. }
  91636. return lastNode;
  91637. };
  91638. /**
  91639. * Traverses nodes and creates them
  91640. */
  91641. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91642. if (meshIncluded === void 0) { meshIncluded = false; }
  91643. var node = gltfRuntime.nodes[id];
  91644. var newNode = null;
  91645. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91646. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91647. meshIncluded = true;
  91648. }
  91649. else {
  91650. meshIncluded = false;
  91651. }
  91652. }
  91653. else {
  91654. meshIncluded = true;
  91655. }
  91656. if (!node.jointName && meshIncluded) {
  91657. newNode = importNode(gltfRuntime, node, id, parent);
  91658. if (newNode !== null) {
  91659. newNode.id = id;
  91660. newNode.parent = parent;
  91661. }
  91662. }
  91663. if (node.children) {
  91664. for (var i = 0; i < node.children.length; i++) {
  91665. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91666. }
  91667. }
  91668. };
  91669. /**
  91670. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91671. */
  91672. var postLoad = function (gltfRuntime) {
  91673. // Nodes
  91674. var currentScene = gltfRuntime.currentScene;
  91675. if (currentScene) {
  91676. for (var i = 0; i < currentScene.nodes.length; i++) {
  91677. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91678. }
  91679. }
  91680. else {
  91681. for (var thing in gltfRuntime.scenes) {
  91682. currentScene = gltfRuntime.scenes[thing];
  91683. for (var i = 0; i < currentScene.nodes.length; i++) {
  91684. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91685. }
  91686. }
  91687. }
  91688. // Set animations
  91689. loadAnimations(gltfRuntime);
  91690. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91691. var skeleton = gltfRuntime.scene.skeletons[i];
  91692. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91693. }
  91694. };
  91695. /**
  91696. * onBind shaderrs callback to set uniforms and matrices
  91697. */
  91698. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91699. var materialValues = material.values || technique.parameters;
  91700. for (var unif in unTreatedUniforms) {
  91701. var uniform = unTreatedUniforms[unif];
  91702. var type = uniform.type;
  91703. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91704. if (uniform.semantic && !uniform.source && !uniform.node) {
  91705. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91706. }
  91707. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91708. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91709. if (source === null) {
  91710. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91711. }
  91712. if (source === null) {
  91713. continue;
  91714. }
  91715. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91716. }
  91717. }
  91718. else {
  91719. var value = materialValues[technique.uniforms[unif]];
  91720. if (!value) {
  91721. continue;
  91722. }
  91723. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91724. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91725. if (texture === null || texture === undefined) {
  91726. continue;
  91727. }
  91728. shaderMaterial.getEffect().setTexture(unif, texture);
  91729. }
  91730. else {
  91731. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91732. }
  91733. }
  91734. }
  91735. onSuccess(shaderMaterial);
  91736. };
  91737. /**
  91738. * Prepare uniforms to send the only one time
  91739. * Loads the appropriate textures
  91740. */
  91741. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91742. var materialValues = material.values || technique.parameters;
  91743. var techniqueUniforms = technique.uniforms;
  91744. /**
  91745. * Prepare values here (not matrices)
  91746. */
  91747. for (var unif in unTreatedUniforms) {
  91748. var uniform = unTreatedUniforms[unif];
  91749. var type = uniform.type;
  91750. var value = materialValues[techniqueUniforms[unif]];
  91751. if (value === undefined) {
  91752. // In case the value is the same for all materials
  91753. value = uniform.value;
  91754. }
  91755. if (!value) {
  91756. continue;
  91757. }
  91758. var onLoadTexture = function (uniformName) {
  91759. return function (texture) {
  91760. if (uniform.value && uniformName) {
  91761. // Static uniform
  91762. shaderMaterial.setTexture(uniformName, texture);
  91763. delete unTreatedUniforms[uniformName];
  91764. }
  91765. };
  91766. };
  91767. // Texture (sampler2D)
  91768. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91769. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91770. }
  91771. else {
  91772. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91773. // Static uniform
  91774. delete unTreatedUniforms[unif];
  91775. }
  91776. }
  91777. }
  91778. };
  91779. /**
  91780. * Shader compilation failed
  91781. */
  91782. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91783. return function (effect, error) {
  91784. shaderMaterial.dispose(true);
  91785. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91786. };
  91787. };
  91788. /**
  91789. * Shader compilation success
  91790. */
  91791. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91792. return function (_) {
  91793. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91794. shaderMaterial.onBind = function (mesh) {
  91795. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91796. };
  91797. };
  91798. };
  91799. /**
  91800. * Returns the appropriate uniform if already handled by babylon
  91801. */
  91802. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91803. for (var unif in technique.uniforms) {
  91804. var uniform = technique.uniforms[unif];
  91805. var uniformParameter = technique.parameters[uniform];
  91806. if (tokenizer.currentIdentifier === unif) {
  91807. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91808. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91809. if (transformIndex !== -1) {
  91810. delete unTreatedUniforms[unif];
  91811. return babylonTransforms[transformIndex];
  91812. }
  91813. }
  91814. }
  91815. }
  91816. return tokenizer.currentIdentifier;
  91817. };
  91818. /**
  91819. * All shaders loaded. Create materials one by one
  91820. */
  91821. var importMaterials = function (gltfRuntime) {
  91822. // Create materials
  91823. for (var mat in gltfRuntime.materials) {
  91824. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91825. }
  91826. };
  91827. /**
  91828. * Implementation of the base glTF spec
  91829. */
  91830. var GLTFLoaderBase = /** @class */ (function () {
  91831. function GLTFLoaderBase() {
  91832. }
  91833. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91834. var gltfRuntime = {
  91835. extensions: {},
  91836. accessors: {},
  91837. buffers: {},
  91838. bufferViews: {},
  91839. meshes: {},
  91840. lights: {},
  91841. cameras: {},
  91842. nodes: {},
  91843. images: {},
  91844. textures: {},
  91845. shaders: {},
  91846. programs: {},
  91847. samplers: {},
  91848. techniques: {},
  91849. materials: {},
  91850. animations: {},
  91851. skins: {},
  91852. extensionsUsed: [],
  91853. scenes: {},
  91854. buffersCount: 0,
  91855. shaderscount: 0,
  91856. scene: scene,
  91857. rootUrl: rootUrl,
  91858. loadedBufferCount: 0,
  91859. loadedBufferViews: {},
  91860. loadedShaderCount: 0,
  91861. importOnlyMeshes: false,
  91862. dummyNodes: []
  91863. };
  91864. // Parse
  91865. if (parsedData.extensions) {
  91866. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91867. }
  91868. if (parsedData.extensionsUsed) {
  91869. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91870. }
  91871. if (parsedData.buffers) {
  91872. parseBuffers(parsedData.buffers, gltfRuntime);
  91873. }
  91874. if (parsedData.bufferViews) {
  91875. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91876. }
  91877. if (parsedData.accessors) {
  91878. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91879. }
  91880. if (parsedData.meshes) {
  91881. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91882. }
  91883. if (parsedData.lights) {
  91884. parseObject(parsedData.lights, "lights", gltfRuntime);
  91885. }
  91886. if (parsedData.cameras) {
  91887. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91888. }
  91889. if (parsedData.nodes) {
  91890. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91891. }
  91892. if (parsedData.images) {
  91893. parseObject(parsedData.images, "images", gltfRuntime);
  91894. }
  91895. if (parsedData.textures) {
  91896. parseObject(parsedData.textures, "textures", gltfRuntime);
  91897. }
  91898. if (parsedData.shaders) {
  91899. parseShaders(parsedData.shaders, gltfRuntime);
  91900. }
  91901. if (parsedData.programs) {
  91902. parseObject(parsedData.programs, "programs", gltfRuntime);
  91903. }
  91904. if (parsedData.samplers) {
  91905. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91906. }
  91907. if (parsedData.techniques) {
  91908. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91909. }
  91910. if (parsedData.materials) {
  91911. parseObject(parsedData.materials, "materials", gltfRuntime);
  91912. }
  91913. if (parsedData.animations) {
  91914. parseObject(parsedData.animations, "animations", gltfRuntime);
  91915. }
  91916. if (parsedData.skins) {
  91917. parseObject(parsedData.skins, "skins", gltfRuntime);
  91918. }
  91919. if (parsedData.scenes) {
  91920. gltfRuntime.scenes = parsedData.scenes;
  91921. }
  91922. if (parsedData.scene && parsedData.scenes) {
  91923. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91924. }
  91925. return gltfRuntime;
  91926. };
  91927. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91928. var buffer = gltfRuntime.buffers[id];
  91929. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91930. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91931. }
  91932. else {
  91933. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91934. if (request) {
  91935. onError(request.status + " " + request.statusText);
  91936. }
  91937. });
  91938. }
  91939. };
  91940. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91941. var texture = gltfRuntime.textures[id];
  91942. if (!texture || !texture.source) {
  91943. onError("");
  91944. return;
  91945. }
  91946. if (texture.babylonTexture) {
  91947. onSuccess(null);
  91948. return;
  91949. }
  91950. var source = gltfRuntime.images[texture.source];
  91951. if (BABYLON.Tools.IsBase64(source.uri)) {
  91952. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91953. }
  91954. else {
  91955. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91956. if (request) {
  91957. onError(request.status + " " + request.statusText);
  91958. }
  91959. });
  91960. }
  91961. };
  91962. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91963. var texture = gltfRuntime.textures[id];
  91964. if (texture.babylonTexture) {
  91965. onSuccess(texture.babylonTexture);
  91966. return;
  91967. }
  91968. var sampler = gltfRuntime.samplers[texture.sampler];
  91969. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91970. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91971. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91972. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91973. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91974. var blob = new Blob([buffer]);
  91975. var blobURL = URL.createObjectURL(blob);
  91976. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91977. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91978. if (sampler.wrapS !== undefined) {
  91979. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91980. }
  91981. if (sampler.wrapT !== undefined) {
  91982. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91983. }
  91984. newTexture.name = id;
  91985. texture.babylonTexture = newTexture;
  91986. onSuccess(newTexture);
  91987. };
  91988. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91989. var shader = gltfRuntime.shaders[id];
  91990. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91991. var shaderString = atob(shader.uri.split(",")[1]);
  91992. onSuccess(shaderString);
  91993. }
  91994. else {
  91995. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91996. if (request) {
  91997. onError(request.status + " " + request.statusText);
  91998. }
  91999. });
  92000. }
  92001. };
  92002. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92003. var material = gltfRuntime.materials[id];
  92004. if (!material.technique) {
  92005. if (onError) {
  92006. onError("No technique found.");
  92007. }
  92008. return;
  92009. }
  92010. var technique = gltfRuntime.techniques[material.technique];
  92011. if (!technique) {
  92012. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92013. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  92014. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92015. onSuccess(defaultMaterial);
  92016. return;
  92017. }
  92018. var program = gltfRuntime.programs[technique.program];
  92019. var states = technique.states;
  92020. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  92021. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  92022. var newVertexShader = "";
  92023. var newPixelShader = "";
  92024. var vertexTokenizer = new Tokenizer(vertexShader);
  92025. var pixelTokenizer = new Tokenizer(pixelShader);
  92026. var unTreatedUniforms = {};
  92027. var uniforms = [];
  92028. var attributes = [];
  92029. var samplers = [];
  92030. // Fill uniform, sampler2D and attributes
  92031. for (var unif in technique.uniforms) {
  92032. var uniform = technique.uniforms[unif];
  92033. var uniformParameter = technique.parameters[uniform];
  92034. unTreatedUniforms[unif] = uniformParameter;
  92035. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  92036. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  92037. if (transformIndex !== -1) {
  92038. uniforms.push(babylonTransforms[transformIndex]);
  92039. delete unTreatedUniforms[unif];
  92040. }
  92041. else {
  92042. uniforms.push(unif);
  92043. }
  92044. }
  92045. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  92046. samplers.push(unif);
  92047. }
  92048. else {
  92049. uniforms.push(unif);
  92050. }
  92051. }
  92052. for (var attr in technique.attributes) {
  92053. var attribute = technique.attributes[attr];
  92054. var attributeParameter = technique.parameters[attribute];
  92055. if (attributeParameter.semantic) {
  92056. attributes.push(getAttribute(attributeParameter));
  92057. }
  92058. }
  92059. // Configure vertex shader
  92060. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  92061. var tokenType = vertexTokenizer.currentToken;
  92062. if (tokenType !== ETokenType.IDENTIFIER) {
  92063. newVertexShader += vertexTokenizer.currentString;
  92064. continue;
  92065. }
  92066. var foundAttribute = false;
  92067. for (var attr in technique.attributes) {
  92068. var attribute = technique.attributes[attr];
  92069. var attributeParameter = technique.parameters[attribute];
  92070. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  92071. newVertexShader += getAttribute(attributeParameter);
  92072. foundAttribute = true;
  92073. break;
  92074. }
  92075. }
  92076. if (foundAttribute) {
  92077. continue;
  92078. }
  92079. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  92080. }
  92081. // Configure pixel shader
  92082. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  92083. var tokenType = pixelTokenizer.currentToken;
  92084. if (tokenType !== ETokenType.IDENTIFIER) {
  92085. newPixelShader += pixelTokenizer.currentString;
  92086. continue;
  92087. }
  92088. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  92089. }
  92090. // Create shader material
  92091. var shaderPath = {
  92092. vertex: program.vertexShader + id,
  92093. fragment: program.fragmentShader + id
  92094. };
  92095. var options = {
  92096. attributes: attributes,
  92097. uniforms: uniforms,
  92098. samplers: samplers,
  92099. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  92100. };
  92101. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  92102. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  92103. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  92104. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  92105. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  92106. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92107. if (states && states.functions) {
  92108. var functions = states.functions;
  92109. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  92110. shaderMaterial.backFaceCulling = false;
  92111. }
  92112. var blendFunc = functions.blendFuncSeparate;
  92113. if (blendFunc) {
  92114. 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) {
  92115. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  92116. }
  92117. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92118. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92119. }
  92120. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92121. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  92122. }
  92123. 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) {
  92124. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  92125. }
  92126. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92127. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  92128. }
  92129. 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) {
  92130. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  92131. }
  92132. }
  92133. }
  92134. };
  92135. return GLTFLoaderBase;
  92136. }());
  92137. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  92138. /**
  92139. * glTF V1 Loader
  92140. */
  92141. var GLTFLoader = /** @class */ (function () {
  92142. function GLTFLoader() {
  92143. // #region Stubs for IGLTFLoader interface
  92144. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92145. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92146. this.compileMaterials = false;
  92147. this.useClipPlane = false;
  92148. this.compileShadowGenerators = false;
  92149. this.onDisposeObservable = new BABYLON.Observable();
  92150. this.onMeshLoadedObservable = new BABYLON.Observable();
  92151. this.onTextureLoadedObservable = new BABYLON.Observable();
  92152. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92153. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92154. this.onCompleteObservable = new BABYLON.Observable();
  92155. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92156. this.state = null;
  92157. }
  92158. GLTFLoader.RegisterExtension = function (extension) {
  92159. if (GLTFLoader.Extensions[extension.name]) {
  92160. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  92161. return;
  92162. }
  92163. GLTFLoader.Extensions[extension.name] = extension;
  92164. };
  92165. GLTFLoader.prototype.dispose = function () { };
  92166. // #endregion
  92167. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  92168. var _this = this;
  92169. scene.useRightHandedSystem = true;
  92170. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92171. gltfRuntime.importOnlyMeshes = true;
  92172. if (meshesNames === "") {
  92173. gltfRuntime.importMeshesNames = [];
  92174. }
  92175. else if (typeof meshesNames === "string") {
  92176. gltfRuntime.importMeshesNames = [meshesNames];
  92177. }
  92178. else if (meshesNames && !(meshesNames instanceof Array)) {
  92179. gltfRuntime.importMeshesNames = [meshesNames];
  92180. }
  92181. else {
  92182. gltfRuntime.importMeshesNames = [];
  92183. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  92184. }
  92185. // Create nodes
  92186. _this._createNodes(gltfRuntime);
  92187. var meshes = new Array();
  92188. var skeletons = new Array();
  92189. // Fill arrays of meshes and skeletons
  92190. for (var nde in gltfRuntime.nodes) {
  92191. var node = gltfRuntime.nodes[nde];
  92192. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  92193. meshes.push(node.babylonNode);
  92194. }
  92195. }
  92196. for (var skl in gltfRuntime.skins) {
  92197. var skin = gltfRuntime.skins[skl];
  92198. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  92199. skeletons.push(skin.babylonSkeleton);
  92200. }
  92201. }
  92202. // Load buffers, shaders, materials, etc.
  92203. _this._loadBuffersAsync(gltfRuntime, function () {
  92204. _this._loadShadersAsync(gltfRuntime, function () {
  92205. importMaterials(gltfRuntime);
  92206. postLoad(gltfRuntime);
  92207. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92208. onSuccess(meshes, [], skeletons);
  92209. }
  92210. });
  92211. }, onProgress);
  92212. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92213. onSuccess(meshes, [], skeletons);
  92214. }
  92215. }, onError);
  92216. return true;
  92217. };
  92218. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92219. var _this = this;
  92220. return new Promise(function (resolve, reject) {
  92221. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  92222. resolve({
  92223. meshes: meshes,
  92224. particleSystems: particleSystems,
  92225. skeletons: skeletons
  92226. });
  92227. }, onProgress, function (message) {
  92228. reject(new Error(message));
  92229. });
  92230. });
  92231. };
  92232. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  92233. var _this = this;
  92234. scene.useRightHandedSystem = true;
  92235. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92236. // Load runtime extensios
  92237. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  92238. // Create nodes
  92239. _this._createNodes(gltfRuntime);
  92240. // Load buffers, shaders, materials, etc.
  92241. _this._loadBuffersAsync(gltfRuntime, function () {
  92242. _this._loadShadersAsync(gltfRuntime, function () {
  92243. importMaterials(gltfRuntime);
  92244. postLoad(gltfRuntime);
  92245. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  92246. onSuccess();
  92247. }
  92248. });
  92249. });
  92250. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  92251. onSuccess();
  92252. }
  92253. }, onError);
  92254. }, onError);
  92255. };
  92256. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92257. var _this = this;
  92258. return new Promise(function (resolve, reject) {
  92259. _this._loadAsync(scene, data, rootUrl, function () {
  92260. resolve();
  92261. }, onProgress, function (message) {
  92262. reject(new Error(message));
  92263. });
  92264. });
  92265. };
  92266. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  92267. var hasShaders = false;
  92268. var processShader = function (sha, shader) {
  92269. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  92270. gltfRuntime.loadedShaderCount++;
  92271. if (shaderString) {
  92272. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  92273. }
  92274. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  92275. onload();
  92276. }
  92277. }, function () {
  92278. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  92279. });
  92280. };
  92281. for (var sha in gltfRuntime.shaders) {
  92282. hasShaders = true;
  92283. var shader = gltfRuntime.shaders[sha];
  92284. if (shader) {
  92285. processShader.bind(this, sha, shader)();
  92286. }
  92287. else {
  92288. BABYLON.Tools.Error("No shader named: " + sha);
  92289. }
  92290. }
  92291. if (!hasShaders) {
  92292. onload();
  92293. }
  92294. };
  92295. ;
  92296. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  92297. var hasBuffers = false;
  92298. var processBuffer = function (buf, buffer) {
  92299. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  92300. gltfRuntime.loadedBufferCount++;
  92301. if (bufferView) {
  92302. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  92303. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  92304. }
  92305. gltfRuntime.loadedBufferViews[buf] = bufferView;
  92306. }
  92307. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  92308. onLoad();
  92309. }
  92310. }, function () {
  92311. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  92312. });
  92313. };
  92314. for (var buf in gltfRuntime.buffers) {
  92315. hasBuffers = true;
  92316. var buffer = gltfRuntime.buffers[buf];
  92317. if (buffer) {
  92318. processBuffer.bind(this, buf, buffer)();
  92319. }
  92320. else {
  92321. BABYLON.Tools.Error("No buffer named: " + buf);
  92322. }
  92323. }
  92324. if (!hasBuffers) {
  92325. onLoad();
  92326. }
  92327. };
  92328. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  92329. var currentScene = gltfRuntime.currentScene;
  92330. if (currentScene) {
  92331. // Only one scene even if multiple scenes are defined
  92332. for (var i = 0; i < currentScene.nodes.length; i++) {
  92333. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92334. }
  92335. }
  92336. else {
  92337. // Load all scenes
  92338. for (var thing in gltfRuntime.scenes) {
  92339. currentScene = gltfRuntime.scenes[thing];
  92340. for (var i = 0; i < currentScene.nodes.length; i++) {
  92341. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92342. }
  92343. }
  92344. }
  92345. };
  92346. GLTFLoader.Extensions = {};
  92347. return GLTFLoader;
  92348. }());
  92349. GLTF1.GLTFLoader = GLTFLoader;
  92350. ;
  92351. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  92352. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92353. })(BABYLON || (BABYLON = {}));
  92354. //# sourceMappingURL=babylon.glTFLoader.js.map
  92355. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92356. var BABYLON;
  92357. (function (BABYLON) {
  92358. var GLTF1;
  92359. (function (GLTF1) {
  92360. /**
  92361. * Utils functions for GLTF
  92362. */
  92363. var GLTFUtils = /** @class */ (function () {
  92364. function GLTFUtils() {
  92365. }
  92366. /**
  92367. * Sets the given "parameter" matrix
  92368. * @param scene: the {BABYLON.Scene} object
  92369. * @param source: the source node where to pick the matrix
  92370. * @param parameter: the GLTF technique parameter
  92371. * @param uniformName: the name of the shader's uniform
  92372. * @param shaderMaterial: the shader material
  92373. */
  92374. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  92375. var mat = null;
  92376. if (parameter.semantic === "MODEL") {
  92377. mat = source.getWorldMatrix();
  92378. }
  92379. else if (parameter.semantic === "PROJECTION") {
  92380. mat = scene.getProjectionMatrix();
  92381. }
  92382. else if (parameter.semantic === "VIEW") {
  92383. mat = scene.getViewMatrix();
  92384. }
  92385. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  92386. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  92387. }
  92388. else if (parameter.semantic === "MODELVIEW") {
  92389. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  92390. }
  92391. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  92392. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  92393. }
  92394. else if (parameter.semantic === "MODELINVERSE") {
  92395. mat = source.getWorldMatrix().invert();
  92396. }
  92397. else if (parameter.semantic === "VIEWINVERSE") {
  92398. mat = scene.getViewMatrix().invert();
  92399. }
  92400. else if (parameter.semantic === "PROJECTIONINVERSE") {
  92401. mat = scene.getProjectionMatrix().invert();
  92402. }
  92403. else if (parameter.semantic === "MODELVIEWINVERSE") {
  92404. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  92405. }
  92406. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  92407. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  92408. }
  92409. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  92410. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  92411. }
  92412. else {
  92413. debugger;
  92414. }
  92415. if (mat) {
  92416. switch (parameter.type) {
  92417. case GLTF1.EParameterType.FLOAT_MAT2:
  92418. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  92419. break;
  92420. case GLTF1.EParameterType.FLOAT_MAT3:
  92421. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  92422. break;
  92423. case GLTF1.EParameterType.FLOAT_MAT4:
  92424. shaderMaterial.setMatrix(uniformName, mat);
  92425. break;
  92426. default: break;
  92427. }
  92428. }
  92429. };
  92430. /**
  92431. * Sets the given "parameter" matrix
  92432. * @param shaderMaterial: the shader material
  92433. * @param uniform: the name of the shader's uniform
  92434. * @param value: the value of the uniform
  92435. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  92436. */
  92437. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  92438. switch (type) {
  92439. case GLTF1.EParameterType.FLOAT:
  92440. shaderMaterial.setFloat(uniform, value);
  92441. return true;
  92442. case GLTF1.EParameterType.FLOAT_VEC2:
  92443. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  92444. return true;
  92445. case GLTF1.EParameterType.FLOAT_VEC3:
  92446. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  92447. return true;
  92448. case GLTF1.EParameterType.FLOAT_VEC4:
  92449. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  92450. return true;
  92451. default: return false;
  92452. }
  92453. };
  92454. /**
  92455. * Returns the wrap mode of the texture
  92456. * @param mode: the mode value
  92457. */
  92458. GLTFUtils.GetWrapMode = function (mode) {
  92459. switch (mode) {
  92460. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92461. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92462. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92463. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92464. }
  92465. };
  92466. /**
  92467. * Returns the byte stride giving an accessor
  92468. * @param accessor: the GLTF accessor objet
  92469. */
  92470. GLTFUtils.GetByteStrideFromType = function (accessor) {
  92471. // Needs this function since "byteStride" isn't requiered in glTF format
  92472. var type = accessor.type;
  92473. switch (type) {
  92474. case "VEC2": return 2;
  92475. case "VEC3": return 3;
  92476. case "VEC4": return 4;
  92477. case "MAT2": return 4;
  92478. case "MAT3": return 9;
  92479. case "MAT4": return 16;
  92480. default: return 1;
  92481. }
  92482. };
  92483. /**
  92484. * Returns the texture filter mode giving a mode value
  92485. * @param mode: the filter mode value
  92486. */
  92487. GLTFUtils.GetTextureFilterMode = function (mode) {
  92488. switch (mode) {
  92489. case GLTF1.ETextureFilterType.LINEAR:
  92490. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  92491. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92492. case GLTF1.ETextureFilterType.NEAREST:
  92493. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  92494. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92495. }
  92496. };
  92497. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  92498. var byteOffset = bufferView.byteOffset + byteOffset;
  92499. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  92500. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  92501. throw new Error("Buffer access is out of range");
  92502. }
  92503. var buffer = loadedBufferView.buffer;
  92504. byteOffset += loadedBufferView.byteOffset;
  92505. switch (componentType) {
  92506. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  92507. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  92508. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  92509. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  92510. default: return new Float32Array(buffer, byteOffset, byteLength);
  92511. }
  92512. };
  92513. /**
  92514. * Returns a buffer from its accessor
  92515. * @param gltfRuntime: the GLTF runtime
  92516. * @param accessor: the GLTF accessor
  92517. */
  92518. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  92519. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  92520. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  92521. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  92522. };
  92523. /**
  92524. * Decodes a buffer view into a string
  92525. * @param view: the buffer view
  92526. */
  92527. GLTFUtils.DecodeBufferToText = function (view) {
  92528. var result = "";
  92529. var length = view.byteLength;
  92530. for (var i = 0; i < length; ++i) {
  92531. result += String.fromCharCode(view[i]);
  92532. }
  92533. return result;
  92534. };
  92535. /**
  92536. * Returns the default material of gltf. Related to
  92537. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  92538. * @param scene: the Babylon.js scene
  92539. */
  92540. GLTFUtils.GetDefaultMaterial = function (scene) {
  92541. if (!GLTFUtils._DefaultMaterial) {
  92542. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  92543. "precision highp float;",
  92544. "",
  92545. "uniform mat4 worldView;",
  92546. "uniform mat4 projection;",
  92547. "",
  92548. "attribute vec3 position;",
  92549. "",
  92550. "void main(void)",
  92551. "{",
  92552. " gl_Position = projection * worldView * vec4(position, 1.0);",
  92553. "}"
  92554. ].join("\n");
  92555. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  92556. "precision highp float;",
  92557. "",
  92558. "uniform vec4 u_emission;",
  92559. "",
  92560. "void main(void)",
  92561. "{",
  92562. " gl_FragColor = u_emission;",
  92563. "}"
  92564. ].join("\n");
  92565. var shaderPath = {
  92566. vertex: "GLTFDefaultMaterial",
  92567. fragment: "GLTFDefaultMaterial"
  92568. };
  92569. var options = {
  92570. attributes: ["position"],
  92571. uniforms: ["worldView", "projection", "u_emission"],
  92572. samplers: new Array(),
  92573. needAlphaBlending: false
  92574. };
  92575. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  92576. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  92577. }
  92578. return GLTFUtils._DefaultMaterial;
  92579. };
  92580. // The GLTF default material
  92581. GLTFUtils._DefaultMaterial = null;
  92582. return GLTFUtils;
  92583. }());
  92584. GLTF1.GLTFUtils = GLTFUtils;
  92585. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92586. })(BABYLON || (BABYLON = {}));
  92587. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  92588. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92589. var BABYLON;
  92590. (function (BABYLON) {
  92591. var GLTF1;
  92592. (function (GLTF1) {
  92593. var GLTFLoaderExtension = /** @class */ (function () {
  92594. function GLTFLoaderExtension(name) {
  92595. this._name = name;
  92596. }
  92597. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92598. get: function () {
  92599. return this._name;
  92600. },
  92601. enumerable: true,
  92602. configurable: true
  92603. });
  92604. /**
  92605. * Defines an override for loading the runtime
  92606. * Return true to stop further extensions from loading the runtime
  92607. */
  92608. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92609. return false;
  92610. };
  92611. /**
  92612. * Defines an onverride for creating gltf runtime
  92613. * Return true to stop further extensions from creating the runtime
  92614. */
  92615. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92616. return false;
  92617. };
  92618. /**
  92619. * Defines an override for loading buffers
  92620. * Return true to stop further extensions from loading this buffer
  92621. */
  92622. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92623. return false;
  92624. };
  92625. /**
  92626. * Defines an override for loading texture buffers
  92627. * Return true to stop further extensions from loading this texture data
  92628. */
  92629. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92630. return false;
  92631. };
  92632. /**
  92633. * Defines an override for creating textures
  92634. * Return true to stop further extensions from loading this texture
  92635. */
  92636. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92637. return false;
  92638. };
  92639. /**
  92640. * Defines an override for loading shader strings
  92641. * Return true to stop further extensions from loading this shader data
  92642. */
  92643. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92644. return false;
  92645. };
  92646. /**
  92647. * Defines an override for loading materials
  92648. * Return true to stop further extensions from loading this material
  92649. */
  92650. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92651. return false;
  92652. };
  92653. // ---------
  92654. // Utilities
  92655. // ---------
  92656. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92657. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92658. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92659. }, function () {
  92660. setTimeout(function () {
  92661. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92662. });
  92663. });
  92664. };
  92665. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92666. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92667. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92668. }, function () {
  92669. setTimeout(function () {
  92670. onSuccess();
  92671. });
  92672. });
  92673. };
  92674. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92675. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92676. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92677. }, function () {
  92678. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92679. });
  92680. };
  92681. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92682. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92683. };
  92684. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92685. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92686. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92687. }, function () {
  92688. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92689. });
  92690. };
  92691. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92692. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92693. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92694. }, function () {
  92695. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92696. });
  92697. };
  92698. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92699. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92700. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92701. }, function () {
  92702. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92703. });
  92704. };
  92705. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92706. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92707. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92708. }, function () {
  92709. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92710. });
  92711. };
  92712. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92713. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92714. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92715. if (func(loaderExtension)) {
  92716. return;
  92717. }
  92718. }
  92719. defaultFunc();
  92720. };
  92721. return GLTFLoaderExtension;
  92722. }());
  92723. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92724. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92725. })(BABYLON || (BABYLON = {}));
  92726. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92727. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92728. var BABYLON;
  92729. (function (BABYLON) {
  92730. var GLTF1;
  92731. (function (GLTF1) {
  92732. var BinaryExtensionBufferName = "binary_glTF";
  92733. ;
  92734. ;
  92735. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92736. __extends(GLTFBinaryExtension, _super);
  92737. function GLTFBinaryExtension() {
  92738. return _super.call(this, "KHR_binary_glTF") || this;
  92739. }
  92740. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92741. var extensionsUsed = data.json.extensionsUsed;
  92742. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92743. return false;
  92744. }
  92745. this._bin = data.bin;
  92746. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92747. return true;
  92748. };
  92749. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92750. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92751. return false;
  92752. }
  92753. if (id !== BinaryExtensionBufferName) {
  92754. return false;
  92755. }
  92756. onSuccess(this._bin);
  92757. return true;
  92758. };
  92759. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92760. var texture = gltfRuntime.textures[id];
  92761. var source = gltfRuntime.images[texture.source];
  92762. if (!source.extensions || !(this.name in source.extensions)) {
  92763. return false;
  92764. }
  92765. var sourceExt = source.extensions[this.name];
  92766. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92767. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92768. onSuccess(buffer);
  92769. return true;
  92770. };
  92771. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92772. var shader = gltfRuntime.shaders[id];
  92773. if (!shader.extensions || !(this.name in shader.extensions)) {
  92774. return false;
  92775. }
  92776. var binaryExtensionShader = shader.extensions[this.name];
  92777. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92778. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92779. setTimeout(function () {
  92780. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92781. onSuccess(shaderString);
  92782. });
  92783. return true;
  92784. };
  92785. return GLTFBinaryExtension;
  92786. }(GLTF1.GLTFLoaderExtension));
  92787. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92788. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92789. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92790. })(BABYLON || (BABYLON = {}));
  92791. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92792. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92793. var BABYLON;
  92794. (function (BABYLON) {
  92795. var GLTF1;
  92796. (function (GLTF1) {
  92797. ;
  92798. ;
  92799. ;
  92800. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92801. __extends(GLTFMaterialsCommonExtension, _super);
  92802. function GLTFMaterialsCommonExtension() {
  92803. return _super.call(this, "KHR_materials_common") || this;
  92804. }
  92805. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92806. if (!gltfRuntime.extensions)
  92807. return false;
  92808. var extension = gltfRuntime.extensions[this.name];
  92809. if (!extension)
  92810. return false;
  92811. // Create lights
  92812. var lights = extension.lights;
  92813. if (lights) {
  92814. for (var thing in lights) {
  92815. var light = lights[thing];
  92816. switch (light.type) {
  92817. case "ambient":
  92818. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92819. var ambient = light.ambient;
  92820. if (ambient) {
  92821. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92822. }
  92823. break;
  92824. case "point":
  92825. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92826. var point = light.point;
  92827. if (point) {
  92828. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92829. }
  92830. break;
  92831. case "directional":
  92832. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92833. var directional = light.directional;
  92834. if (directional) {
  92835. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92836. }
  92837. break;
  92838. case "spot":
  92839. var spot = light.spot;
  92840. if (spot) {
  92841. 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);
  92842. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92843. }
  92844. break;
  92845. default:
  92846. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92847. break;
  92848. }
  92849. }
  92850. }
  92851. return false;
  92852. };
  92853. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92854. var material = gltfRuntime.materials[id];
  92855. if (!material || !material.extensions)
  92856. return false;
  92857. var extension = material.extensions[this.name];
  92858. if (!extension)
  92859. return false;
  92860. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92861. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92862. if (extension.technique === "CONSTANT") {
  92863. standardMaterial.disableLighting = true;
  92864. }
  92865. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92866. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92867. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92868. // Ambient
  92869. if (typeof extension.values.ambient === "string") {
  92870. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92871. }
  92872. else {
  92873. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92874. }
  92875. // Diffuse
  92876. if (typeof extension.values.diffuse === "string") {
  92877. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92878. }
  92879. else {
  92880. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92881. }
  92882. // Emission
  92883. if (typeof extension.values.emission === "string") {
  92884. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92885. }
  92886. else {
  92887. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92888. }
  92889. // Specular
  92890. if (typeof extension.values.specular === "string") {
  92891. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92892. }
  92893. else {
  92894. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92895. }
  92896. return true;
  92897. };
  92898. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92899. // Create buffer from texture url
  92900. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92901. // Create texture from buffer
  92902. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92903. }, onError);
  92904. };
  92905. return GLTFMaterialsCommonExtension;
  92906. }(GLTF1.GLTFLoaderExtension));
  92907. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92908. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92909. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92910. })(BABYLON || (BABYLON = {}));
  92911. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92912. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92913. var BABYLON;
  92914. (function (BABYLON) {
  92915. var GLTF2;
  92916. (function (GLTF2) {
  92917. var ArrayItem = /** @class */ (function () {
  92918. function ArrayItem() {
  92919. }
  92920. ArrayItem.Assign = function (values) {
  92921. if (values) {
  92922. for (var index = 0; index < values.length; index++) {
  92923. values[index]._index = index;
  92924. }
  92925. }
  92926. };
  92927. return ArrayItem;
  92928. }());
  92929. GLTF2.ArrayItem = ArrayItem;
  92930. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92931. })(BABYLON || (BABYLON = {}));
  92932. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92933. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92934. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92935. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92936. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92937. var BABYLON;
  92938. (function (BABYLON) {
  92939. var GLTF2;
  92940. (function (GLTF2) {
  92941. var GLTFLoader = /** @class */ (function () {
  92942. function GLTFLoader() {
  92943. this._completePromises = new Array();
  92944. this._disposed = false;
  92945. this._state = null;
  92946. this._extensions = {};
  92947. this._defaultSampler = {};
  92948. this._requests = new Array();
  92949. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92950. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92951. this.compileMaterials = false;
  92952. this.useClipPlane = false;
  92953. this.compileShadowGenerators = false;
  92954. this.onDisposeObservable = new BABYLON.Observable();
  92955. this.onMeshLoadedObservable = new BABYLON.Observable();
  92956. this.onTextureLoadedObservable = new BABYLON.Observable();
  92957. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92958. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92959. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92960. this.onCompleteObservable = new BABYLON.Observable();
  92961. }
  92962. GLTFLoader._Register = function (name, factory) {
  92963. if (GLTFLoader._Factories[name]) {
  92964. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92965. return;
  92966. }
  92967. GLTFLoader._Factories[name] = factory;
  92968. // Keep the order of registration so that extensions registered first are called first.
  92969. GLTFLoader._Names.push(name);
  92970. };
  92971. Object.defineProperty(GLTFLoader.prototype, "state", {
  92972. get: function () {
  92973. return this._state;
  92974. },
  92975. enumerable: true,
  92976. configurable: true
  92977. });
  92978. GLTFLoader.prototype.dispose = function () {
  92979. if (this._disposed) {
  92980. return;
  92981. }
  92982. this._disposed = true;
  92983. this.onDisposeObservable.notifyObservers(this);
  92984. this.onDisposeObservable.clear();
  92985. this._clear();
  92986. };
  92987. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92988. var _this = this;
  92989. return Promise.resolve().then(function () {
  92990. var nodes = null;
  92991. if (meshesNames) {
  92992. var nodeMap_1 = {};
  92993. if (_this._gltf.nodes) {
  92994. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92995. var node = _a[_i];
  92996. if (node.name) {
  92997. nodeMap_1[node.name] = node;
  92998. }
  92999. }
  93000. }
  93001. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  93002. nodes = names.map(function (name) {
  93003. var node = nodeMap_1[name];
  93004. if (!node) {
  93005. throw new Error("Failed to find node '" + name + "'");
  93006. }
  93007. return node;
  93008. });
  93009. }
  93010. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  93011. return {
  93012. meshes: _this._getMeshes(),
  93013. particleSystems: [],
  93014. skeletons: _this._getSkeletons(),
  93015. };
  93016. });
  93017. });
  93018. };
  93019. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  93020. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  93021. };
  93022. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  93023. var _this = this;
  93024. return Promise.resolve().then(function () {
  93025. _this._loadExtensions();
  93026. _this._babylonScene = scene;
  93027. _this._rootUrl = rootUrl;
  93028. _this._progressCallback = onProgress;
  93029. _this._state = BABYLON.GLTFLoaderState.Loading;
  93030. _this._loadData(data);
  93031. _this._checkExtensions();
  93032. var promises = new Array();
  93033. if (nodes) {
  93034. promises.push(_this._loadNodesAsync(nodes));
  93035. }
  93036. else {
  93037. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  93038. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  93039. }
  93040. if (_this.compileMaterials) {
  93041. promises.push(_this._compileMaterialsAsync());
  93042. }
  93043. if (_this.compileShadowGenerators) {
  93044. promises.push(_this._compileShadowGeneratorsAsync());
  93045. }
  93046. var resultPromise = Promise.all(promises).then(function () {
  93047. _this._state = BABYLON.GLTFLoaderState.Ready;
  93048. _this._startAnimations();
  93049. });
  93050. resultPromise.then(function () {
  93051. _this._rootBabylonMesh.setEnabled(true);
  93052. BABYLON.Tools.SetImmediate(function () {
  93053. if (!_this._disposed) {
  93054. Promise.all(_this._completePromises).then(function () {
  93055. _this._state = BABYLON.GLTFLoaderState.Complete;
  93056. _this.onCompleteObservable.notifyObservers(_this);
  93057. _this.onCompleteObservable.clear();
  93058. _this._clear();
  93059. }).catch(function (error) {
  93060. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93061. _this._clear();
  93062. });
  93063. }
  93064. });
  93065. });
  93066. return resultPromise;
  93067. }).catch(function (error) {
  93068. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93069. _this._clear();
  93070. throw error;
  93071. });
  93072. };
  93073. GLTFLoader.prototype._loadExtensions = function () {
  93074. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93075. var name_1 = _a[_i];
  93076. var extension = GLTFLoader._Factories[name_1](this);
  93077. this._extensions[name_1] = extension;
  93078. this.onExtensionLoadedObservable.notifyObservers(extension);
  93079. }
  93080. this.onExtensionLoadedObservable.clear();
  93081. };
  93082. GLTFLoader.prototype._loadData = function (data) {
  93083. this._gltf = data.json;
  93084. this._setupData();
  93085. if (data.bin) {
  93086. var buffers = this._gltf.buffers;
  93087. if (buffers && buffers[0] && !buffers[0].uri) {
  93088. var binaryBuffer = buffers[0];
  93089. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  93090. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  93091. }
  93092. binaryBuffer._data = Promise.resolve(data.bin);
  93093. }
  93094. else {
  93095. BABYLON.Tools.Warn("Unexpected BIN chunk");
  93096. }
  93097. }
  93098. };
  93099. GLTFLoader.prototype._setupData = function () {
  93100. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  93101. GLTF2.ArrayItem.Assign(this._gltf.animations);
  93102. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  93103. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  93104. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  93105. GLTF2.ArrayItem.Assign(this._gltf.images);
  93106. GLTF2.ArrayItem.Assign(this._gltf.materials);
  93107. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  93108. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  93109. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  93110. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  93111. GLTF2.ArrayItem.Assign(this._gltf.skins);
  93112. GLTF2.ArrayItem.Assign(this._gltf.textures);
  93113. if (this._gltf.nodes) {
  93114. var nodeParents = {};
  93115. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  93116. var node = _a[_i];
  93117. if (node.children) {
  93118. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  93119. var index = _c[_b];
  93120. nodeParents[index] = node._index;
  93121. }
  93122. }
  93123. }
  93124. var rootNode = this._createRootNode();
  93125. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  93126. var node = _e[_d];
  93127. var parentIndex = nodeParents[node._index];
  93128. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  93129. }
  93130. }
  93131. };
  93132. GLTFLoader.prototype._checkExtensions = function () {
  93133. if (this._gltf.extensionsRequired) {
  93134. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  93135. var name_2 = _a[_i];
  93136. var extension = this._extensions[name_2];
  93137. if (!extension || !extension.enabled) {
  93138. throw new Error("Require extension " + name_2 + " is not available");
  93139. }
  93140. }
  93141. }
  93142. };
  93143. GLTFLoader.prototype._createRootNode = function () {
  93144. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  93145. this._rootBabylonMesh.setEnabled(false);
  93146. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  93147. switch (this.coordinateSystemMode) {
  93148. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  93149. if (!this._babylonScene.useRightHandedSystem) {
  93150. rootNode.rotation = [0, 1, 0, 0];
  93151. rootNode.scale = [1, 1, -1];
  93152. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  93153. }
  93154. break;
  93155. }
  93156. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  93157. this._babylonScene.useRightHandedSystem = true;
  93158. break;
  93159. }
  93160. default: {
  93161. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  93162. }
  93163. }
  93164. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  93165. return rootNode;
  93166. };
  93167. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  93168. var promises = new Array();
  93169. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  93170. var node = nodes_1[_i];
  93171. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93172. }
  93173. promises.push(this._loadAnimationsAsync());
  93174. return Promise.all(promises).then(function () { });
  93175. };
  93176. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  93177. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  93178. if (promise) {
  93179. return promise;
  93180. }
  93181. var promises = new Array();
  93182. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  93183. var index = _a[_i];
  93184. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  93185. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93186. }
  93187. promises.push(this._loadAnimationsAsync());
  93188. return Promise.all(promises).then(function () { });
  93189. };
  93190. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  93191. if (node._babylonMesh) {
  93192. callback(node._babylonMesh);
  93193. }
  93194. if (node._primitiveBabylonMeshes) {
  93195. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  93196. var babylonMesh = _a[_i];
  93197. callback(babylonMesh);
  93198. }
  93199. }
  93200. };
  93201. GLTFLoader.prototype._getMeshes = function () {
  93202. var meshes = new Array();
  93203. // Root mesh is always first.
  93204. meshes.push(this._rootBabylonMesh);
  93205. var nodes = this._gltf.nodes;
  93206. if (nodes) {
  93207. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  93208. var node = nodes_2[_i];
  93209. this._forEachNodeMesh(node, function (mesh) {
  93210. meshes.push(mesh);
  93211. });
  93212. }
  93213. }
  93214. return meshes;
  93215. };
  93216. GLTFLoader.prototype._getSkeletons = function () {
  93217. var skeletons = new Array();
  93218. var skins = this._gltf.skins;
  93219. if (skins) {
  93220. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  93221. var skin = skins_1[_i];
  93222. if (skin._babylonSkeleton) {
  93223. skeletons.push(skin._babylonSkeleton);
  93224. }
  93225. }
  93226. }
  93227. return skeletons;
  93228. };
  93229. GLTFLoader.prototype._startAnimations = function () {
  93230. var animations = this._gltf.animations;
  93231. if (!animations) {
  93232. return;
  93233. }
  93234. switch (this.animationStartMode) {
  93235. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  93236. // do nothing
  93237. break;
  93238. }
  93239. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  93240. var animation = animations[0];
  93241. animation._babylonAnimationGroup.start(true);
  93242. break;
  93243. }
  93244. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  93245. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  93246. var animation = animations_1[_i];
  93247. animation._babylonAnimationGroup.start(true);
  93248. }
  93249. break;
  93250. }
  93251. default: {
  93252. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  93253. return;
  93254. }
  93255. }
  93256. };
  93257. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  93258. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  93259. if (promise) {
  93260. return promise;
  93261. }
  93262. if (node._babylonMesh) {
  93263. throw new Error(context + ": Invalid recursive node hierarchy");
  93264. }
  93265. var promises = new Array();
  93266. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  93267. node._babylonMesh = babylonMesh;
  93268. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93269. node._babylonAnimationTargets.push(babylonMesh);
  93270. GLTFLoader._LoadTransform(node, babylonMesh);
  93271. if (node.mesh != undefined) {
  93272. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  93273. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  93274. }
  93275. if (node.children) {
  93276. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  93277. var index = _a[_i];
  93278. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  93279. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  93280. }
  93281. }
  93282. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93283. return Promise.all(promises).then(function () { });
  93284. };
  93285. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  93286. // TODO: instancing
  93287. var _this = this;
  93288. var promises = new Array();
  93289. var primitives = mesh.primitives;
  93290. if (!primitives || primitives.length === 0) {
  93291. throw new Error(context + ": Primitives are missing");
  93292. }
  93293. GLTF2.ArrayItem.Assign(primitives);
  93294. if (primitives.length === 1) {
  93295. var primitive = primitives[0];
  93296. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  93297. }
  93298. else {
  93299. node._primitiveBabylonMeshes = [];
  93300. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  93301. var primitive = primitives_1[_i];
  93302. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  93303. node._primitiveBabylonMeshes.push(babylonMesh);
  93304. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  93305. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93306. }
  93307. }
  93308. if (node.skin != undefined) {
  93309. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  93310. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  93311. }
  93312. return Promise.all(promises).then(function () {
  93313. _this._forEachNodeMesh(node, function (babylonMesh) {
  93314. babylonMesh._refreshBoundingInfo(true);
  93315. });
  93316. });
  93317. };
  93318. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  93319. var _this = this;
  93320. var promises = new Array();
  93321. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  93322. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  93323. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  93324. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  93325. }));
  93326. if (primitive.material == undefined) {
  93327. babylonMesh.material = this._getDefaultMaterial();
  93328. }
  93329. else {
  93330. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  93331. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  93332. babylonMesh.material = babylonMaterial;
  93333. }));
  93334. }
  93335. return Promise.all(promises).then(function () { });
  93336. };
  93337. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93338. var _this = this;
  93339. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  93340. if (promise) {
  93341. return promise;
  93342. }
  93343. var attributes = primitive.attributes;
  93344. if (!attributes) {
  93345. throw new Error(context + ": Attributes are missing");
  93346. }
  93347. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  93348. // TODO: handle other primitive modes
  93349. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  93350. }
  93351. var promises = new Array();
  93352. var babylonVertexData = new BABYLON.VertexData();
  93353. if (primitive.indices == undefined) {
  93354. var positionAccessorIndex = attributes["POSITION"];
  93355. if (positionAccessorIndex != undefined) {
  93356. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  93357. babylonVertexData.indices = new Uint32Array(accessor.count);
  93358. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  93359. babylonVertexData.indices[i] = i;
  93360. }
  93361. }
  93362. }
  93363. else {
  93364. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  93365. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  93366. babylonVertexData.indices = data;
  93367. }));
  93368. }
  93369. var loadAttribute = function (attribute, kind) {
  93370. if (attributes[attribute] == undefined) {
  93371. return;
  93372. }
  93373. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93374. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93375. babylonMesh._delayInfo.push(kind);
  93376. }
  93377. if (attribute === "COLOR_0") {
  93378. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  93379. babylonMesh.hasVertexAlpha = true;
  93380. }
  93381. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93382. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93383. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  93384. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  93385. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  93386. }
  93387. babylonVertexData.set(attributeData, kind);
  93388. }));
  93389. };
  93390. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93391. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93392. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93393. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93394. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93395. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93396. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93397. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93398. return Promise.all(promises).then(function () {
  93399. return babylonVertexData;
  93400. });
  93401. };
  93402. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  93403. if (!primitive.targets) {
  93404. return;
  93405. }
  93406. if (node._numMorphTargets == undefined) {
  93407. node._numMorphTargets = primitive.targets.length;
  93408. }
  93409. else if (primitive.targets.length !== node._numMorphTargets) {
  93410. throw new Error(context + ": Primitives do not have the same number of targets");
  93411. }
  93412. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  93413. for (var index = 0; index < primitive.targets.length; index++) {
  93414. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  93415. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  93416. // TODO: tell the target whether it has positions, normals, tangents
  93417. }
  93418. };
  93419. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  93420. if (!primitive.targets) {
  93421. return Promise.resolve();
  93422. }
  93423. var promises = new Array();
  93424. var morphTargetManager = babylonMesh.morphTargetManager;
  93425. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  93426. var babylonMorphTarget = morphTargetManager.getTarget(index);
  93427. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  93428. }
  93429. return Promise.all(promises).then(function () { });
  93430. };
  93431. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  93432. var _this = this;
  93433. var promises = new Array();
  93434. var loadAttribute = function (attribute, setData) {
  93435. if (attributes[attribute] == undefined) {
  93436. return;
  93437. }
  93438. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93439. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93440. setData(data);
  93441. }));
  93442. };
  93443. loadAttribute("POSITION", function (data) {
  93444. if (babylonVertexData.positions) {
  93445. for (var i = 0; i < data.length; i++) {
  93446. data[i] += babylonVertexData.positions[i];
  93447. }
  93448. babylonMorphTarget.setPositions(data);
  93449. }
  93450. });
  93451. loadAttribute("NORMAL", function (data) {
  93452. if (babylonVertexData.normals) {
  93453. for (var i = 0; i < data.length; i++) {
  93454. data[i] += babylonVertexData.normals[i];
  93455. }
  93456. babylonMorphTarget.setNormals(data);
  93457. }
  93458. });
  93459. loadAttribute("TANGENT", function (data) {
  93460. if (babylonVertexData.tangents) {
  93461. // Tangent data for morph targets is stored as xyz delta.
  93462. // The vertexData.tangent is stored as xyzw.
  93463. // So we need to skip every fourth vertexData.tangent.
  93464. for (var i = 0, j = 0; i < data.length; i++) {
  93465. data[i] += babylonVertexData.tangents[j++];
  93466. if ((i + 1) % 3 == 0) {
  93467. j++;
  93468. }
  93469. }
  93470. babylonMorphTarget.setTangents(data);
  93471. }
  93472. });
  93473. return Promise.all(promises).then(function () { });
  93474. };
  93475. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  93476. if (accessor.componentType == 5126 /* FLOAT */) {
  93477. return data;
  93478. }
  93479. var factor = 1;
  93480. if (accessor.normalized) {
  93481. switch (accessor.componentType) {
  93482. case 5121 /* UNSIGNED_BYTE */: {
  93483. factor = 1 / 255;
  93484. break;
  93485. }
  93486. case 5123 /* UNSIGNED_SHORT */: {
  93487. factor = 1 / 65535;
  93488. break;
  93489. }
  93490. default: {
  93491. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93492. }
  93493. }
  93494. }
  93495. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  93496. for (var i = 0; i < result.length; i++) {
  93497. result[i] = data[i] * factor;
  93498. }
  93499. return result;
  93500. };
  93501. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  93502. var result = new Float32Array(data.length / 3 * 4);
  93503. var offset = 0;
  93504. for (var i = 0; i < result.length; i++) {
  93505. if ((i + 1) % 4 === 0) {
  93506. result[i] = 1;
  93507. }
  93508. else {
  93509. result[i] = data[offset++];
  93510. }
  93511. }
  93512. return result;
  93513. };
  93514. GLTFLoader._LoadTransform = function (node, babylonNode) {
  93515. var position = BABYLON.Vector3.Zero();
  93516. var rotation = BABYLON.Quaternion.Identity();
  93517. var scaling = BABYLON.Vector3.One();
  93518. if (node.matrix) {
  93519. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  93520. matrix.decompose(scaling, rotation, position);
  93521. }
  93522. else {
  93523. if (node.translation)
  93524. position = BABYLON.Vector3.FromArray(node.translation);
  93525. if (node.rotation)
  93526. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  93527. if (node.scale)
  93528. scaling = BABYLON.Vector3.FromArray(node.scale);
  93529. }
  93530. babylonNode.position = position;
  93531. babylonNode.rotationQuaternion = rotation;
  93532. babylonNode.scaling = scaling;
  93533. };
  93534. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  93535. var _this = this;
  93536. var assignSkeleton = function () {
  93537. _this._forEachNodeMesh(node, function (babylonMesh) {
  93538. babylonMesh.skeleton = skin._babylonSkeleton;
  93539. });
  93540. node._babylonMesh.parent = _this._rootBabylonMesh;
  93541. node._babylonMesh.position = BABYLON.Vector3.Zero();
  93542. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  93543. node._babylonMesh.scaling = BABYLON.Vector3.One();
  93544. };
  93545. if (skin._loaded) {
  93546. return skin._loaded.then(function () {
  93547. assignSkeleton();
  93548. });
  93549. }
  93550. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  93551. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  93552. var skeletonId = "skeleton" + skin._index;
  93553. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  93554. skin._babylonSkeleton = babylonSkeleton;
  93555. _this._loadBones(context, skin, inverseBindMatricesData);
  93556. assignSkeleton();
  93557. }));
  93558. };
  93559. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  93560. if (skin.inverseBindMatrices == undefined) {
  93561. return Promise.resolve(null);
  93562. }
  93563. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  93564. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93565. return data;
  93566. });
  93567. };
  93568. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  93569. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  93570. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93571. node._babylonAnimationTargets.push(babylonBone);
  93572. return babylonBone;
  93573. };
  93574. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  93575. var babylonBones = {};
  93576. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  93577. var index = _a[_i];
  93578. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  93579. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  93580. }
  93581. };
  93582. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  93583. var babylonBone = babylonBones[node._index];
  93584. if (babylonBone) {
  93585. return babylonBone;
  93586. }
  93587. var boneIndex = skin.joints.indexOf(node._index);
  93588. var baseMatrix = BABYLON.Matrix.Identity();
  93589. if (inverseBindMatricesData && boneIndex !== -1) {
  93590. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  93591. baseMatrix.invertToRef(baseMatrix);
  93592. }
  93593. var babylonParentBone = null;
  93594. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  93595. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  93596. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  93597. }
  93598. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  93599. babylonBones[node._index] = babylonBone;
  93600. return babylonBone;
  93601. };
  93602. GLTFLoader.prototype._getNodeMatrix = function (node) {
  93603. return node.matrix ?
  93604. BABYLON.Matrix.FromArray(node.matrix) :
  93605. 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());
  93606. };
  93607. GLTFLoader.prototype._loadAnimationsAsync = function () {
  93608. var animations = this._gltf.animations;
  93609. if (!animations) {
  93610. return Promise.resolve();
  93611. }
  93612. var promises = new Array();
  93613. for (var index = 0; index < animations.length; index++) {
  93614. var animation = animations[index];
  93615. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93616. }
  93617. return Promise.all(promises).then(function () { });
  93618. };
  93619. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93620. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93621. animation._babylonAnimationGroup = babylonAnimationGroup;
  93622. var promises = new Array();
  93623. GLTF2.ArrayItem.Assign(animation.channels);
  93624. GLTF2.ArrayItem.Assign(animation.samplers);
  93625. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93626. var channel = _a[_i];
  93627. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93628. }
  93629. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  93630. return Promise.all(promises).then(function () {
  93631. babylonAnimationGroup.normalize();
  93632. });
  93633. };
  93634. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93635. var _this = this;
  93636. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93637. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  93638. return Promise.resolve();
  93639. }
  93640. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93641. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93642. var targetPath;
  93643. var animationType;
  93644. switch (channel.target.path) {
  93645. case "translation" /* TRANSLATION */: {
  93646. targetPath = "position";
  93647. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93648. break;
  93649. }
  93650. case "rotation" /* ROTATION */: {
  93651. targetPath = "rotationQuaternion";
  93652. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93653. break;
  93654. }
  93655. case "scale" /* SCALE */: {
  93656. targetPath = "scaling";
  93657. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93658. break;
  93659. }
  93660. case "weights" /* WEIGHTS */: {
  93661. targetPath = "influence";
  93662. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93663. break;
  93664. }
  93665. default: {
  93666. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  93667. }
  93668. }
  93669. var outputBufferOffset = 0;
  93670. var getNextOutputValue;
  93671. switch (targetPath) {
  93672. case "position": {
  93673. getNextOutputValue = function () {
  93674. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93675. outputBufferOffset += 3;
  93676. return value;
  93677. };
  93678. break;
  93679. }
  93680. case "rotationQuaternion": {
  93681. getNextOutputValue = function () {
  93682. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93683. outputBufferOffset += 4;
  93684. return value;
  93685. };
  93686. break;
  93687. }
  93688. case "scaling": {
  93689. getNextOutputValue = function () {
  93690. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93691. outputBufferOffset += 3;
  93692. return value;
  93693. };
  93694. break;
  93695. }
  93696. case "influence": {
  93697. getNextOutputValue = function () {
  93698. var value = new Array(targetNode._numMorphTargets);
  93699. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93700. value[i] = data.output[outputBufferOffset++];
  93701. }
  93702. return value;
  93703. };
  93704. break;
  93705. }
  93706. }
  93707. var getNextKey;
  93708. switch (data.interpolation) {
  93709. case "STEP" /* STEP */: {
  93710. getNextKey = function (frameIndex) { return ({
  93711. frame: data.input[frameIndex],
  93712. value: getNextOutputValue(),
  93713. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93714. }); };
  93715. break;
  93716. }
  93717. case "LINEAR" /* LINEAR */: {
  93718. getNextKey = function (frameIndex) { return ({
  93719. frame: data.input[frameIndex],
  93720. value: getNextOutputValue()
  93721. }); };
  93722. break;
  93723. }
  93724. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93725. getNextKey = function (frameIndex) { return ({
  93726. frame: data.input[frameIndex],
  93727. inTangent: getNextOutputValue(),
  93728. value: getNextOutputValue(),
  93729. outTangent: getNextOutputValue()
  93730. }); };
  93731. break;
  93732. }
  93733. }
  93734. var keys;
  93735. if (data.input.length === 1) {
  93736. var key = getNextKey(0);
  93737. keys = [
  93738. { frame: key.frame, value: key.value },
  93739. { frame: key.frame + 1, value: key.value }
  93740. ];
  93741. }
  93742. else {
  93743. keys = new Array(data.input.length);
  93744. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93745. keys[frameIndex] = getNextKey(frameIndex);
  93746. }
  93747. }
  93748. if (targetPath === "influence") {
  93749. var _loop_1 = function (targetIndex) {
  93750. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93751. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93752. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93753. frame: key.frame,
  93754. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93755. value: key.value[targetIndex],
  93756. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93757. }); }));
  93758. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  93759. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93760. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93761. });
  93762. };
  93763. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93764. _loop_1(targetIndex);
  93765. }
  93766. }
  93767. else {
  93768. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93769. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93770. babylonAnimation.setKeys(keys);
  93771. if (targetNode._babylonAnimationTargets) {
  93772. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93773. var target = _a[_i];
  93774. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93775. }
  93776. }
  93777. }
  93778. });
  93779. };
  93780. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93781. if (sampler._data) {
  93782. return sampler._data;
  93783. }
  93784. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93785. switch (interpolation) {
  93786. case "STEP" /* STEP */:
  93787. case "LINEAR" /* LINEAR */:
  93788. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93789. break;
  93790. }
  93791. default: {
  93792. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  93793. }
  93794. }
  93795. var inputData;
  93796. var outputData;
  93797. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93798. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93799. sampler._data = Promise.all([
  93800. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93801. inputData = data;
  93802. }),
  93803. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93804. outputData = data;
  93805. })
  93806. ]).then(function () {
  93807. return {
  93808. input: inputData,
  93809. interpolation: interpolation,
  93810. output: outputData,
  93811. };
  93812. });
  93813. return sampler._data;
  93814. };
  93815. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93816. if (buffer._data) {
  93817. return buffer._data;
  93818. }
  93819. if (!buffer.uri) {
  93820. throw new Error(context + ": Uri is missing");
  93821. }
  93822. buffer._data = this._loadUriAsync(context, buffer.uri);
  93823. return buffer._data;
  93824. };
  93825. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93826. if (bufferView._data) {
  93827. return bufferView._data;
  93828. }
  93829. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93830. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93831. try {
  93832. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93833. }
  93834. catch (e) {
  93835. throw new Error(context + ": " + e.message);
  93836. }
  93837. });
  93838. return bufferView._data;
  93839. };
  93840. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93841. var _this = this;
  93842. if (accessor.sparse) {
  93843. throw new Error(context + ": Sparse accessors are not currently supported");
  93844. }
  93845. if (accessor._data) {
  93846. return accessor._data;
  93847. }
  93848. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93849. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93850. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93851. var byteOffset = accessor.byteOffset || 0;
  93852. var byteStride = bufferView.byteStride;
  93853. if (byteStride === 0) {
  93854. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93855. }
  93856. try {
  93857. switch (accessor.componentType) {
  93858. case 5120 /* BYTE */: {
  93859. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93860. }
  93861. case 5121 /* UNSIGNED_BYTE */: {
  93862. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93863. }
  93864. case 5122 /* SHORT */: {
  93865. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93866. }
  93867. case 5123 /* UNSIGNED_SHORT */: {
  93868. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93869. }
  93870. case 5125 /* UNSIGNED_INT */: {
  93871. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93872. }
  93873. case 5126 /* FLOAT */: {
  93874. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93875. }
  93876. default: {
  93877. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93878. }
  93879. }
  93880. }
  93881. catch (e) {
  93882. throw new Error(context + ": " + e.messsage);
  93883. }
  93884. });
  93885. return accessor._data;
  93886. };
  93887. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93888. byteOffset += data.byteOffset;
  93889. var targetLength = count * numComponents;
  93890. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93891. return new typedArray(data.buffer, byteOffset, targetLength);
  93892. }
  93893. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93894. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93895. var targetBuffer = new typedArray(targetLength);
  93896. var sourceIndex = 0;
  93897. var targetIndex = 0;
  93898. while (targetIndex < targetLength) {
  93899. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93900. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93901. targetIndex++;
  93902. }
  93903. sourceIndex += elementStride;
  93904. }
  93905. return targetBuffer;
  93906. };
  93907. GLTFLoader.prototype._getDefaultMaterial = function () {
  93908. var id = "__gltf_default";
  93909. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93910. if (!babylonMaterial) {
  93911. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93912. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93913. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93914. babylonMaterial.metallic = 1;
  93915. babylonMaterial.roughness = 1;
  93916. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93917. }
  93918. return babylonMaterial;
  93919. };
  93920. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93921. var promises = new Array();
  93922. var babylonMaterial = material._babylonMaterial;
  93923. // Ensure metallic workflow
  93924. babylonMaterial.metallic = 1;
  93925. babylonMaterial.roughness = 1;
  93926. var properties = material.pbrMetallicRoughness;
  93927. if (properties) {
  93928. if (properties.baseColorFactor) {
  93929. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93930. babylonMaterial.alpha = properties.baseColorFactor[3];
  93931. }
  93932. else {
  93933. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93934. }
  93935. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93936. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93937. if (properties.baseColorTexture) {
  93938. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93939. babylonMaterial.albedoTexture = texture;
  93940. }));
  93941. }
  93942. if (properties.metallicRoughnessTexture) {
  93943. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93944. babylonMaterial.metallicTexture = texture;
  93945. }));
  93946. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93947. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93948. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93949. }
  93950. }
  93951. this._loadMaterialAlphaProperties(context, material);
  93952. return Promise.all(promises).then(function () { });
  93953. };
  93954. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93955. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  93956. if (promise) {
  93957. return promise;
  93958. }
  93959. material._babylonMeshes = material._babylonMeshes || [];
  93960. material._babylonMeshes.push(babylonMesh);
  93961. if (!material._loaded) {
  93962. var promises = new Array();
  93963. var babylonMaterial = this._createMaterial(material);
  93964. material._babylonMaterial = babylonMaterial;
  93965. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93966. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93967. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93968. material._loaded = Promise.all(promises).then(function () { });
  93969. }
  93970. assign(material._babylonMaterial);
  93971. return material._loaded;
  93972. };
  93973. GLTFLoader.prototype._createMaterial = function (material) {
  93974. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93975. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93976. return babylonMaterial;
  93977. };
  93978. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93979. var promises = new Array();
  93980. var babylonMaterial = material._babylonMaterial;
  93981. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93982. if (material.doubleSided) {
  93983. babylonMaterial.backFaceCulling = false;
  93984. babylonMaterial.twoSidedLighting = true;
  93985. }
  93986. if (material.normalTexture) {
  93987. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93988. babylonMaterial.bumpTexture = texture;
  93989. }));
  93990. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93991. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93992. if (material.normalTexture.scale != undefined) {
  93993. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93994. }
  93995. }
  93996. if (material.occlusionTexture) {
  93997. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93998. babylonMaterial.ambientTexture = texture;
  93999. }));
  94000. babylonMaterial.useAmbientInGrayScale = true;
  94001. if (material.occlusionTexture.strength != undefined) {
  94002. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  94003. }
  94004. }
  94005. if (material.emissiveTexture) {
  94006. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  94007. babylonMaterial.emissiveTexture = texture;
  94008. }));
  94009. }
  94010. return Promise.all(promises).then(function () { });
  94011. };
  94012. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  94013. var babylonMaterial = material._babylonMaterial;
  94014. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  94015. switch (alphaMode) {
  94016. case "OPAQUE" /* OPAQUE */: {
  94017. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  94018. break;
  94019. }
  94020. case "MASK" /* MASK */: {
  94021. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  94022. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  94023. if (babylonMaterial.alpha) {
  94024. if (babylonMaterial.alpha === 0) {
  94025. babylonMaterial.alphaCutOff = 1;
  94026. }
  94027. else {
  94028. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  94029. }
  94030. babylonMaterial.alpha = 1;
  94031. }
  94032. if (babylonMaterial.albedoTexture) {
  94033. babylonMaterial.albedoTexture.hasAlpha = true;
  94034. }
  94035. break;
  94036. }
  94037. case "BLEND" /* BLEND */: {
  94038. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  94039. if (babylonMaterial.albedoTexture) {
  94040. babylonMaterial.albedoTexture.hasAlpha = true;
  94041. babylonMaterial.useAlphaFromAlbedoTexture = true;
  94042. }
  94043. break;
  94044. }
  94045. default: {
  94046. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  94047. }
  94048. }
  94049. };
  94050. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  94051. var _this = this;
  94052. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  94053. context = "#/textures/" + textureInfo.index;
  94054. var promises = new Array();
  94055. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  94056. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  94057. var deferred = new BABYLON.Deferred();
  94058. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  94059. if (!_this._disposed) {
  94060. deferred.resolve();
  94061. }
  94062. }, function (message, exception) {
  94063. if (!_this._disposed) {
  94064. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  94065. }
  94066. });
  94067. promises.push(deferred.promise);
  94068. babylonTexture.name = texture.name || "texture" + texture._index;
  94069. babylonTexture.wrapU = samplerData.wrapU;
  94070. babylonTexture.wrapV = samplerData.wrapV;
  94071. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  94072. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  94073. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  94074. babylonTexture.updateURL(objectURL);
  94075. }));
  94076. assign(babylonTexture);
  94077. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  94078. return Promise.all(promises).then(function () { });
  94079. };
  94080. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  94081. if (!sampler._data) {
  94082. sampler._data = {
  94083. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  94084. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  94085. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  94086. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  94087. };
  94088. }
  94089. ;
  94090. return sampler._data;
  94091. };
  94092. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  94093. if (image._objectURL) {
  94094. return image._objectURL;
  94095. }
  94096. var promise;
  94097. if (image.uri) {
  94098. promise = this._loadUriAsync(context, image.uri);
  94099. }
  94100. else {
  94101. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  94102. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  94103. }
  94104. image._objectURL = promise.then(function (data) {
  94105. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  94106. });
  94107. return image._objectURL;
  94108. };
  94109. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  94110. var _this = this;
  94111. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  94112. if (promise) {
  94113. return promise;
  94114. }
  94115. if (!GLTFLoader._ValidateUri(uri)) {
  94116. throw new Error(context + ": Uri '" + uri + "' is invalid");
  94117. }
  94118. if (BABYLON.Tools.IsBase64(uri)) {
  94119. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  94120. }
  94121. return new Promise(function (resolve, reject) {
  94122. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  94123. if (!_this._disposed) {
  94124. resolve(new Uint8Array(data));
  94125. }
  94126. }, function (event) {
  94127. if (!_this._disposed) {
  94128. try {
  94129. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  94130. request._lengthComputable = event.lengthComputable;
  94131. request._loaded = event.loaded;
  94132. request._total = event.total;
  94133. _this._onProgress();
  94134. }
  94135. }
  94136. catch (e) {
  94137. reject(e);
  94138. }
  94139. }
  94140. }, _this._babylonScene.database, true, function (request, exception) {
  94141. if (!_this._disposed) {
  94142. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  94143. }
  94144. });
  94145. _this._requests.push(request);
  94146. });
  94147. };
  94148. GLTFLoader.prototype._onProgress = function () {
  94149. if (!this._progressCallback) {
  94150. return;
  94151. }
  94152. var lengthComputable = true;
  94153. var loaded = 0;
  94154. var total = 0;
  94155. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94156. var request = _a[_i];
  94157. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  94158. return;
  94159. }
  94160. lengthComputable = lengthComputable && request._lengthComputable;
  94161. loaded += request._loaded;
  94162. total += request._total;
  94163. }
  94164. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  94165. };
  94166. GLTFLoader._GetProperty = function (context, array, index) {
  94167. if (!array || index == undefined || !array[index]) {
  94168. throw new Error(context + ": Failed to find index (" + index + ")");
  94169. }
  94170. return array[index];
  94171. };
  94172. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  94173. // Set defaults if undefined
  94174. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  94175. switch (mode) {
  94176. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  94177. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  94178. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  94179. default:
  94180. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  94181. return BABYLON.Texture.WRAP_ADDRESSMODE;
  94182. }
  94183. };
  94184. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  94185. // Set defaults if undefined
  94186. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  94187. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  94188. if (magFilter === 9729 /* LINEAR */) {
  94189. switch (minFilter) {
  94190. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  94191. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  94192. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  94193. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  94194. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  94195. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94196. default:
  94197. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94198. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94199. }
  94200. }
  94201. else {
  94202. if (magFilter !== 9728 /* NEAREST */) {
  94203. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  94204. }
  94205. switch (minFilter) {
  94206. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  94207. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  94208. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94209. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  94210. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  94211. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  94212. default:
  94213. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94214. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94215. }
  94216. }
  94217. };
  94218. GLTFLoader._GetNumComponents = function (context, type) {
  94219. switch (type) {
  94220. case "SCALAR": return 1;
  94221. case "VEC2": return 2;
  94222. case "VEC3": return 3;
  94223. case "VEC4": return 4;
  94224. case "MAT2": return 4;
  94225. case "MAT3": return 9;
  94226. case "MAT4": return 16;
  94227. }
  94228. throw new Error(context + ": Invalid type (" + type + ")");
  94229. };
  94230. GLTFLoader._ValidateUri = function (uri) {
  94231. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  94232. };
  94233. GLTFLoader.prototype._compileMaterialsAsync = function () {
  94234. var promises = new Array();
  94235. if (this._gltf.materials) {
  94236. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  94237. var material = _a[_i];
  94238. var babylonMaterial = material._babylonMaterial;
  94239. var babylonMeshes = material._babylonMeshes;
  94240. if (babylonMaterial && babylonMeshes) {
  94241. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  94242. var babylonMesh = babylonMeshes_1[_b];
  94243. // Ensure nonUniformScaling is set if necessary.
  94244. babylonMesh.computeWorldMatrix(true);
  94245. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  94246. if (this.useClipPlane) {
  94247. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  94248. }
  94249. }
  94250. }
  94251. }
  94252. }
  94253. return Promise.all(promises).then(function () { });
  94254. };
  94255. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  94256. var promises = new Array();
  94257. var lights = this._babylonScene.lights;
  94258. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  94259. var light = lights_1[_i];
  94260. var generator = light.getShadowGenerator();
  94261. if (generator) {
  94262. promises.push(generator.forceCompilationAsync());
  94263. }
  94264. }
  94265. return Promise.all(promises).then(function () { });
  94266. };
  94267. GLTFLoader.prototype._clear = function () {
  94268. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94269. var request = _a[_i];
  94270. request.abort();
  94271. }
  94272. this._requests.length = 0;
  94273. if (this._gltf && this._gltf.images) {
  94274. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  94275. var image = _c[_b];
  94276. if (image._objectURL) {
  94277. image._objectURL.then(function (value) {
  94278. URL.revokeObjectURL(value);
  94279. });
  94280. image._objectURL = undefined;
  94281. }
  94282. }
  94283. }
  94284. delete this._gltf;
  94285. delete this._babylonScene;
  94286. this._completePromises.length = 0;
  94287. for (var name_3 in this._extensions) {
  94288. this._extensions[name_3].dispose();
  94289. }
  94290. this._extensions = {};
  94291. delete this._rootBabylonMesh;
  94292. delete this._progressCallback;
  94293. this.onMeshLoadedObservable.clear();
  94294. this.onTextureLoadedObservable.clear();
  94295. this.onMaterialLoadedObservable.clear();
  94296. };
  94297. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  94298. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94299. var name_4 = _a[_i];
  94300. var extension = this._extensions[name_4];
  94301. if (extension.enabled) {
  94302. var promise = actionAsync(extension);
  94303. if (promise) {
  94304. return promise;
  94305. }
  94306. }
  94307. }
  94308. return null;
  94309. };
  94310. GLTFLoader._Names = new Array();
  94311. GLTFLoader._Factories = {};
  94312. return GLTFLoader;
  94313. }());
  94314. GLTF2.GLTFLoader = GLTFLoader;
  94315. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  94316. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94317. })(BABYLON || (BABYLON = {}));
  94318. //# sourceMappingURL=babylon.glTFLoader.js.map
  94319. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94320. var BABYLON;
  94321. (function (BABYLON) {
  94322. var GLTF2;
  94323. (function (GLTF2) {
  94324. var GLTFLoaderExtension = /** @class */ (function () {
  94325. function GLTFLoaderExtension(loader) {
  94326. this.enabled = true;
  94327. this._loader = loader;
  94328. }
  94329. GLTFLoaderExtension.prototype.dispose = function () {
  94330. delete this._loader;
  94331. };
  94332. // #region Overridable Methods
  94333. /** Override this method to modify the default behavior for loading scenes. */
  94334. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  94335. /** Override this method to modify the default behavior for loading nodes. */
  94336. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  94337. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  94338. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  94339. /** Override this method to modify the default behavior for loading materials. */
  94340. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  94341. /** Override this method to modify the default behavior for loading uris. */
  94342. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  94343. // #endregion
  94344. /** Helper method called by a loader extension to load an glTF extension. */
  94345. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  94346. if (!property.extensions) {
  94347. return null;
  94348. }
  94349. var extensions = property.extensions;
  94350. var extension = extensions[this.name];
  94351. if (!extension) {
  94352. return null;
  94353. }
  94354. // Clear out the extension before executing the action to avoid recursing into the same property.
  94355. delete extensions[this.name];
  94356. try {
  94357. return actionAsync(context + "/extensions/" + this.name, extension);
  94358. }
  94359. finally {
  94360. // Restore the extension after executing the action.
  94361. extensions[this.name] = extension;
  94362. }
  94363. };
  94364. /** Helper method called by the loader to allow extensions to override loading scenes. */
  94365. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  94366. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  94367. };
  94368. /** Helper method called by the loader to allow extensions to override loading nodes. */
  94369. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  94370. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  94371. };
  94372. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  94373. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  94374. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  94375. };
  94376. /** Helper method called by the loader to allow extensions to override loading materials. */
  94377. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  94378. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  94379. };
  94380. /** Helper method called by the loader to allow extensions to override loading uris. */
  94381. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  94382. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  94383. };
  94384. return GLTFLoaderExtension;
  94385. }());
  94386. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  94387. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94388. })(BABYLON || (BABYLON = {}));
  94389. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  94390. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94391. var BABYLON;
  94392. (function (BABYLON) {
  94393. var GLTF2;
  94394. (function (GLTF2) {
  94395. var Extensions;
  94396. (function (Extensions) {
  94397. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  94398. var NAME = "MSFT_lod";
  94399. var MSFT_lod = /** @class */ (function (_super) {
  94400. __extends(MSFT_lod, _super);
  94401. function MSFT_lod() {
  94402. var _this = _super !== null && _super.apply(this, arguments) || this;
  94403. _this.name = NAME;
  94404. /**
  94405. * Maximum number of LODs to load, starting from the lowest LOD.
  94406. */
  94407. _this.maxLODsToLoad = Number.MAX_VALUE;
  94408. _this._loadingNodeLOD = null;
  94409. _this._loadNodeSignals = {};
  94410. _this._loadingMaterialLOD = null;
  94411. _this._loadMaterialSignals = {};
  94412. return _this;
  94413. }
  94414. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  94415. var _this = this;
  94416. return this._loadExtensionAsync(context, node, function (context, extension) {
  94417. var firstPromise;
  94418. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  94419. var _loop_1 = function (indexLOD) {
  94420. var nodeLOD = nodeLODs[indexLOD];
  94421. if (indexLOD !== 0) {
  94422. _this._loadingNodeLOD = nodeLOD;
  94423. if (!_this._loadNodeSignals[nodeLOD._index]) {
  94424. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  94425. }
  94426. }
  94427. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  94428. if (indexLOD !== 0) {
  94429. var previousNodeLOD = nodeLODs[indexLOD - 1];
  94430. if (previousNodeLOD._babylonMesh) {
  94431. previousNodeLOD._babylonMesh.dispose();
  94432. delete previousNodeLOD._babylonMesh;
  94433. }
  94434. }
  94435. if (indexLOD !== nodeLODs.length - 1) {
  94436. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  94437. if (_this._loadNodeSignals[nodeIndex]) {
  94438. _this._loadNodeSignals[nodeIndex].resolve();
  94439. delete _this._loadNodeSignals[nodeIndex];
  94440. }
  94441. }
  94442. });
  94443. if (indexLOD === 0) {
  94444. firstPromise = promise;
  94445. }
  94446. else {
  94447. _this._loader._completePromises.push(promise);
  94448. _this._loadingNodeLOD = null;
  94449. }
  94450. };
  94451. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  94452. _loop_1(indexLOD);
  94453. }
  94454. return firstPromise;
  94455. });
  94456. };
  94457. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94458. var _this = this;
  94459. // Don't load material LODs if already loading a node LOD.
  94460. if (this._loadingNodeLOD) {
  94461. return null;
  94462. }
  94463. return this._loadExtensionAsync(context, material, function (context, extension) {
  94464. var firstPromise;
  94465. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  94466. var _loop_2 = function (indexLOD) {
  94467. var materialLOD = materialLODs[indexLOD];
  94468. if (indexLOD !== 0) {
  94469. _this._loadingMaterialLOD = materialLOD;
  94470. if (!_this._loadMaterialSignals[materialLOD._index]) {
  94471. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  94472. }
  94473. }
  94474. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  94475. if (indexLOD !== 0) {
  94476. assign(materialLOD._babylonMaterial);
  94477. var previousMaterialLOD = materialLODs[indexLOD - 1];
  94478. if (previousMaterialLOD._babylonMaterial) {
  94479. previousMaterialLOD._babylonMaterial.dispose();
  94480. delete previousMaterialLOD._babylonMaterial;
  94481. }
  94482. }
  94483. if (indexLOD !== materialLODs.length - 1) {
  94484. var materialIndex = materialLODs[indexLOD + 1]._index;
  94485. if (_this._loadMaterialSignals[materialIndex]) {
  94486. _this._loadMaterialSignals[materialIndex].resolve();
  94487. delete _this._loadMaterialSignals[materialIndex];
  94488. }
  94489. }
  94490. });
  94491. if (indexLOD === 0) {
  94492. firstPromise = promise;
  94493. }
  94494. else {
  94495. _this._loader._completePromises.push(promise);
  94496. _this._loadingMaterialLOD = null;
  94497. }
  94498. };
  94499. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  94500. _loop_2(indexLOD);
  94501. }
  94502. return firstPromise;
  94503. });
  94504. };
  94505. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  94506. var _this = this;
  94507. // Defer the loading of uris if loading a material or node LOD.
  94508. if (this._loadingMaterialLOD) {
  94509. var index = this._loadingMaterialLOD._index;
  94510. return this._loadMaterialSignals[index].promise.then(function () {
  94511. return _this._loader._loadUriAsync(context, uri);
  94512. });
  94513. }
  94514. else if (this._loadingNodeLOD) {
  94515. var index = this._loadingNodeLOD._index;
  94516. return this._loadNodeSignals[index].promise.then(function () {
  94517. return _this._loader._loadUriAsync(context, uri);
  94518. });
  94519. }
  94520. return null;
  94521. };
  94522. /**
  94523. * Gets an array of LOD properties from lowest to highest.
  94524. */
  94525. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  94526. if (this.maxLODsToLoad <= 0) {
  94527. throw new Error("maxLODsToLoad must be greater than zero");
  94528. }
  94529. var properties = new Array();
  94530. for (var i = ids.length - 1; i >= 0; i--) {
  94531. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  94532. if (properties.length === this.maxLODsToLoad) {
  94533. return properties;
  94534. }
  94535. }
  94536. properties.push(property);
  94537. return properties;
  94538. };
  94539. return MSFT_lod;
  94540. }(GLTF2.GLTFLoaderExtension));
  94541. Extensions.MSFT_lod = MSFT_lod;
  94542. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  94543. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94544. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94545. })(BABYLON || (BABYLON = {}));
  94546. //# sourceMappingURL=MSFT_lod.js.map
  94547. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94548. var BABYLON;
  94549. (function (BABYLON) {
  94550. var GLTF2;
  94551. (function (GLTF2) {
  94552. var Extensions;
  94553. (function (Extensions) {
  94554. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  94555. var NAME = "KHR_draco_mesh_compression";
  94556. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  94557. __extends(KHR_draco_mesh_compression, _super);
  94558. function KHR_draco_mesh_compression(loader) {
  94559. var _this = _super.call(this, loader) || this;
  94560. _this.name = NAME;
  94561. _this._dracoCompression = null;
  94562. // Disable extension if decoder is not available.
  94563. if (!BABYLON.DracoCompression.DecoderUrl) {
  94564. _this.enabled = false;
  94565. }
  94566. return _this;
  94567. }
  94568. KHR_draco_mesh_compression.prototype.dispose = function () {
  94569. if (this._dracoCompression) {
  94570. this._dracoCompression.dispose();
  94571. }
  94572. _super.prototype.dispose.call(this);
  94573. };
  94574. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94575. var _this = this;
  94576. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  94577. if (primitive.mode != undefined) {
  94578. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  94579. primitive.mode !== 4 /* TRIANGLES */) {
  94580. throw new Error(context + ": Unsupported mode " + primitive.mode);
  94581. }
  94582. // TODO: handle triangle strips
  94583. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  94584. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  94585. }
  94586. }
  94587. var attributes = {};
  94588. var loadAttribute = function (name, kind) {
  94589. var uniqueId = extension.attributes[name];
  94590. if (uniqueId == undefined) {
  94591. return;
  94592. }
  94593. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94594. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94595. babylonMesh._delayInfo.push(kind);
  94596. }
  94597. attributes[kind] = uniqueId;
  94598. };
  94599. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94600. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94601. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94602. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94603. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94604. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94605. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94606. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94607. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  94608. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  94609. try {
  94610. if (!_this._dracoCompression) {
  94611. _this._dracoCompression = new BABYLON.DracoCompression();
  94612. }
  94613. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  94614. }
  94615. catch (e) {
  94616. throw new Error(context + ": " + e.message);
  94617. }
  94618. });
  94619. });
  94620. };
  94621. return KHR_draco_mesh_compression;
  94622. }(GLTF2.GLTFLoaderExtension));
  94623. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94624. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94625. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94626. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94627. })(BABYLON || (BABYLON = {}));
  94628. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94629. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94630. var BABYLON;
  94631. (function (BABYLON) {
  94632. var GLTF2;
  94633. (function (GLTF2) {
  94634. var Extensions;
  94635. (function (Extensions) {
  94636. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94637. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94638. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94639. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94640. function KHR_materials_pbrSpecularGlossiness() {
  94641. var _this = _super !== null && _super.apply(this, arguments) || this;
  94642. _this.name = NAME;
  94643. return _this;
  94644. }
  94645. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94646. var _this = this;
  94647. return this._loadExtensionAsync(context, material, function (context, extension) {
  94648. material._babylonMeshes = material._babylonMeshes || [];
  94649. material._babylonMeshes.push(babylonMesh);
  94650. if (!material._loaded) {
  94651. var promises = new Array();
  94652. var babylonMaterial = _this._loader._createMaterial(material);
  94653. material._babylonMaterial = babylonMaterial;
  94654. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94655. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  94656. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94657. material._loaded = Promise.all(promises).then(function () { });
  94658. }
  94659. assign(material._babylonMaterial);
  94660. return material._loaded;
  94661. });
  94662. };
  94663. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  94664. var promises = new Array();
  94665. var babylonMaterial = material._babylonMaterial;
  94666. if (properties.diffuseFactor) {
  94667. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94668. babylonMaterial.alpha = properties.diffuseFactor[3];
  94669. }
  94670. else {
  94671. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94672. }
  94673. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94674. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94675. if (properties.diffuseTexture) {
  94676. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94677. babylonMaterial.albedoTexture = texture;
  94678. }));
  94679. }
  94680. if (properties.specularGlossinessTexture) {
  94681. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94682. babylonMaterial.reflectivityTexture = texture;
  94683. }));
  94684. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94685. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94686. }
  94687. this._loader._loadMaterialAlphaProperties(context, material);
  94688. return Promise.all(promises).then(function () { });
  94689. };
  94690. return KHR_materials_pbrSpecularGlossiness;
  94691. }(GLTF2.GLTFLoaderExtension));
  94692. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94693. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94694. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94695. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94696. })(BABYLON || (BABYLON = {}));
  94697. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94698. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94699. var BABYLON;
  94700. (function (BABYLON) {
  94701. var GLTF2;
  94702. (function (GLTF2) {
  94703. var Extensions;
  94704. (function (Extensions) {
  94705. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94706. var NAME = "KHR_lights";
  94707. var LightType;
  94708. (function (LightType) {
  94709. LightType["AMBIENT"] = "ambient";
  94710. LightType["DIRECTIONAL"] = "directional";
  94711. LightType["POINT"] = "point";
  94712. LightType["SPOT"] = "spot";
  94713. })(LightType || (LightType = {}));
  94714. var KHR_lights = /** @class */ (function (_super) {
  94715. __extends(KHR_lights, _super);
  94716. function KHR_lights() {
  94717. var _this = _super !== null && _super.apply(this, arguments) || this;
  94718. _this.name = NAME;
  94719. return _this;
  94720. }
  94721. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94722. var _this = this;
  94723. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94724. var promise = _this._loader._loadSceneAsync(context, scene);
  94725. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94726. if (light.type !== LightType.AMBIENT) {
  94727. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94728. }
  94729. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94730. return promise;
  94731. });
  94732. };
  94733. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94734. var _this = this;
  94735. return this._loadExtensionAsync(context, node, function (context, extension) {
  94736. var promise = _this._loader._loadNodeAsync(context, node);
  94737. var babylonLight;
  94738. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94739. var name = node._babylonMesh.name;
  94740. switch (light.type) {
  94741. case LightType.AMBIENT: {
  94742. throw new Error(context + ": Ambient lights are not allowed on a node");
  94743. }
  94744. case LightType.DIRECTIONAL: {
  94745. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94746. break;
  94747. }
  94748. case LightType.POINT: {
  94749. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94750. break;
  94751. }
  94752. case LightType.SPOT: {
  94753. var spotLight = light;
  94754. // TODO: support inner and outer cone angles
  94755. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94756. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94757. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94758. break;
  94759. }
  94760. default: {
  94761. throw new Error(context + ": Invalid light type (" + light.type + ")");
  94762. }
  94763. }
  94764. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94765. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94766. babylonLight.parent = node._babylonMesh;
  94767. return promise;
  94768. });
  94769. };
  94770. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94771. get: function () {
  94772. var extensions = this._loader._gltf.extensions;
  94773. if (!extensions || !extensions[this.name]) {
  94774. throw new Error("#/extensions: '" + this.name + "' not found");
  94775. }
  94776. var extension = extensions[this.name];
  94777. return extension.lights;
  94778. },
  94779. enumerable: true,
  94780. configurable: true
  94781. });
  94782. return KHR_lights;
  94783. }(GLTF2.GLTFLoaderExtension));
  94784. Extensions.KHR_lights = KHR_lights;
  94785. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94786. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94787. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94788. })(BABYLON || (BABYLON = {}));
  94789. //# sourceMappingURL=KHR_lights.js.map
  94790. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94791. globalObject["BABYLON"] = BABYLON
  94792. return BABYLON;
  94793. });